+ /* Sector to write, starting byte offset within sector. */
+ disk_sector_t sector_idx = byte_to_sector (inode, offset);
+ int sector_ofs = offset % DISK_SECTOR_SIZE;
+
+ /* Bytes left in inode, bytes left in sector, lesser of the two. */
+ off_t inode_left = inode_length (inode) - offset;
+ int sector_left = DISK_SECTOR_SIZE - sector_ofs;
+ int min_left = inode_left < sector_left ? inode_left : sector_left;
+
+ /* Number of bytes to actually write into this sector. */
+ int chunk_size = size < min_left ? size : min_left;
+ if (chunk_size <= 0)
+ break;
+
+ if (sector_ofs == 0 && chunk_size == DISK_SECTOR_SIZE)
+ {
+ /* Write full sector directly to disk. */
+ disk_write (filesys_disk, sector_idx, buffer + bytes_written);
+ }
+ else
+ {
+ /* We need a bounce buffer. */
+ if (bounce == NULL)
+ {
+ bounce = malloc (DISK_SECTOR_SIZE);
+ if (bounce == NULL)
+ break;
+ }
+
+ /* If the sector contains data before or after the chunk
+ we're writing, then we need to read in the sector
+ first. Otherwise we start with a sector of all zeros. */
+ if (sector_ofs > 0 || chunk_size < sector_left)
+ disk_read (filesys_disk, sector_idx, bounce);
+ else
+ memset (bounce, 0, DISK_SECTOR_SIZE);
+ memcpy (bounce + sector_ofs, buffer + bytes_written, chunk_size);
+ disk_write (filesys_disk, sector_idx, bounce);
+ }
+
+ /* Advance. */
+ size -= chunk_size;
+ offset += chunk_size;
+ bytes_written += chunk_size;