patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / fs / reiserfs / stree.c
1 /*
2  *  Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
3  */
4
5 /*
6  *  Written by Anatoly P. Pinchuk pap@namesys.botik.ru
7  *  Programm System Institute
8  *  Pereslavl-Zalessky Russia
9  */
10
11 /*
12  *  This file contains functions dealing with S+tree
13  *
14  * B_IS_IN_TREE
15  * copy_short_key
16  * copy_item_head
17  * comp_short_keys
18  * comp_keys
19  * comp_cpu_keys
20  * comp_short_le_keys
21  * comp_short_cpu_keys
22  * cpu_key2cpu_key
23  * le_key2cpu_key
24  * comp_le_keys
25  * bin_search
26  * get_lkey
27  * get_rkey
28  * key_in_buffer
29  * decrement_bcount
30  * decrement_counters_in_path
31  * reiserfs_check_path
32  * pathrelse_and_restore
33  * pathrelse
34  * search_by_key_reada
35  * search_by_key
36  * search_for_position_by_key
37  * comp_items
38  * prepare_for_direct_item
39  * prepare_for_direntry_item
40  * prepare_for_delete_or_cut
41  * calc_deleted_bytes_number
42  * init_tb_struct
43  * padd_item
44  * reiserfs_delete_item
45  * reiserfs_delete_solid_item
46  * reiserfs_delete_object
47  * maybe_indirect_to_direct
48  * indirect_to_direct_roll_back
49  * reiserfs_cut_from_item
50  * truncate_directory
51  * reiserfs_do_truncate
52  * reiserfs_paste_into_item
53  * reiserfs_insert_item
54  */
55
56 #include <linux/config.h>
57 #include <linux/time.h>
58 #include <linux/string.h>
59 #include <linux/pagemap.h>
60 #include <linux/reiserfs_fs.h>
61 #include <linux/smp_lock.h>
62 #include <linux/buffer_head.h>
63 #include <linux/quotaops.h>
64
65 /* Does the buffer contain a disk block which is in the tree. */
66 inline int B_IS_IN_TREE (const struct buffer_head * p_s_bh)
67 {
68
69   RFALSE( B_LEVEL (p_s_bh) > MAX_HEIGHT,
70           "PAP-1010: block (%b) has too big level (%z)", p_s_bh, p_s_bh);
71
72   return ( B_LEVEL (p_s_bh) != FREE_LEVEL );
73 }
74
75 inline void copy_short_key (void * to, const void * from)
76 {
77     memcpy (to, from, SHORT_KEY_SIZE);
78 }
79
80 //
81 // to gets item head in le form
82 //
83 inline void copy_item_head(struct item_head * p_v_to, 
84                            const struct item_head * p_v_from)
85 {
86   memcpy (p_v_to, p_v_from, IH_SIZE);
87 }
88
89
90 /* k1 is pointer to on-disk structure which is stored in little-endian
91    form. k2 is pointer to cpu variable. For key of items of the same
92    object this returns 0.
93    Returns: -1 if key1 < key2 
94    0 if key1 == key2
95    1 if key1 > key2 */
96 inline int  comp_short_keys (const struct key * le_key, 
97                              const struct cpu_key * cpu_key)
98 {
99   __u32 * p_s_le_u32, * p_s_cpu_u32;
100   int n_key_length = REISERFS_SHORT_KEY_LEN;
101
102   p_s_le_u32 = (__u32 *)le_key;
103   p_s_cpu_u32 = (__u32 *)&cpu_key->on_disk_key;
104   for( ; n_key_length--; ++p_s_le_u32, ++p_s_cpu_u32 ) {
105     if ( le32_to_cpu (*p_s_le_u32) < *p_s_cpu_u32 )
106       return -1;
107     if ( le32_to_cpu (*p_s_le_u32) > *p_s_cpu_u32 )
108       return 1;
109   }
110
111   return 0;
112 }
113
114
115 /* k1 is pointer to on-disk structure which is stored in little-endian
116    form. k2 is pointer to cpu variable.
117    Compare keys using all 4 key fields.
118    Returns: -1 if key1 < key2 0
119    if key1 = key2 1 if key1 > key2 */
120 inline int  comp_keys (const struct key * le_key, const struct cpu_key * cpu_key)
121 {
122   int retval;
123
124   retval = comp_short_keys (le_key, cpu_key);
125   if (retval)
126       return retval;
127   if (le_key_k_offset (le_key_version(le_key), le_key) < cpu_key_k_offset (cpu_key))
128       return -1;
129   if (le_key_k_offset (le_key_version(le_key), le_key) > cpu_key_k_offset (cpu_key))
130       return 1;
131
132   if (cpu_key->key_length == 3)
133       return 0;
134
135   /* this part is needed only when tail conversion is in progress */
136   if (le_key_k_type (le_key_version(le_key), le_key) < cpu_key_k_type (cpu_key))
137     return -1;
138
139   if (le_key_k_type (le_key_version(le_key), le_key) > cpu_key_k_type (cpu_key))
140     return 1;
141
142   return 0;
143 }
144
145
146 //
147 // FIXME: not used yet
148 //
149 inline int comp_cpu_keys (const struct cpu_key * key1, 
150                           const struct cpu_key * key2)
151 {
152     if (key1->on_disk_key.k_dir_id < key2->on_disk_key.k_dir_id)
153         return -1;
154     if (key1->on_disk_key.k_dir_id > key2->on_disk_key.k_dir_id)
155         return 1;
156
157     if (key1->on_disk_key.k_objectid < key2->on_disk_key.k_objectid)
158         return -1;
159     if (key1->on_disk_key.k_objectid > key2->on_disk_key.k_objectid)
160         return 1;
161
162     if (cpu_key_k_offset (key1) < cpu_key_k_offset (key2))
163         return -1;
164     if (cpu_key_k_offset (key1) > cpu_key_k_offset (key2))
165         return 1;
166
167     reiserfs_warning (NULL, "comp_cpu_keys: type are compared for %K and %K",
168                       key1, key2);
169
170     if (cpu_key_k_type (key1) < cpu_key_k_type (key2))
171         return -1;
172     if (cpu_key_k_type (key1) > cpu_key_k_type (key2))
173         return 1;
174     return 0;
175 }
176
177 inline int comp_short_le_keys (const struct key * key1, const struct key * key2)
178 {
179   __u32 * p_s_1_u32, * p_s_2_u32;
180   int n_key_length = REISERFS_SHORT_KEY_LEN;
181
182   p_s_1_u32 = (__u32 *)key1;
183   p_s_2_u32 = (__u32 *)key2;
184   for( ; n_key_length--; ++p_s_1_u32, ++p_s_2_u32 ) {
185     if ( le32_to_cpu (*p_s_1_u32) < le32_to_cpu (*p_s_2_u32) )
186       return -1;
187     if ( le32_to_cpu (*p_s_1_u32) > le32_to_cpu (*p_s_2_u32) )
188       return 1;
189   }
190   return 0;
191 }
192
193 inline int comp_short_cpu_keys (const struct cpu_key * key1, 
194                                 const struct cpu_key * key2)
195 {
196   __u32 * p_s_1_u32, * p_s_2_u32;
197   int n_key_length = REISERFS_SHORT_KEY_LEN;
198
199   p_s_1_u32 = (__u32 *)key1;
200   p_s_2_u32 = (__u32 *)key2;
201
202   for( ; n_key_length--; ++p_s_1_u32, ++p_s_2_u32 ) {
203     if ( *p_s_1_u32 < *p_s_2_u32 )
204       return -1;
205     if ( *p_s_1_u32 > *p_s_2_u32 )
206       return 1;
207   }
208   return 0;
209 }
210
211
212
213 inline void cpu_key2cpu_key (struct cpu_key * to, const struct cpu_key * from)
214 {
215     memcpy (to, from, sizeof (struct cpu_key));
216 }
217
218
219 inline void le_key2cpu_key (struct cpu_key * to, const struct key * from)
220 {
221     to->on_disk_key.k_dir_id = le32_to_cpu (from->k_dir_id);
222     to->on_disk_key.k_objectid = le32_to_cpu (from->k_objectid);
223     
224     // find out version of the key
225     to->version = le_key_version (from);
226     if (to->version == KEY_FORMAT_3_5) {
227         to->on_disk_key.u.k_offset_v1.k_offset = le32_to_cpu (from->u.k_offset_v1.k_offset);
228         to->on_disk_key.u.k_offset_v1.k_uniqueness = le32_to_cpu (from->u.k_offset_v1.k_uniqueness);
229     } else {
230         to->on_disk_key.u.k_offset_v2.k_offset = offset_v2_k_offset(&from->u.k_offset_v2);
231         to->on_disk_key.u.k_offset_v2.k_type = offset_v2_k_type(&from->u.k_offset_v2);
232     } 
233 }
234
235
236
237 // this does not say which one is bigger, it only returns 1 if keys
238 // are not equal, 0 otherwise
239 inline int comp_le_keys (const struct key * k1, const struct key * k2)
240 {
241     return memcmp (k1, k2, sizeof (struct key));
242 }
243
244 /**************************************************************************
245  *  Binary search toolkit function                                        *
246  *  Search for an item in the array by the item key                       *
247  *  Returns:    1 if found,  0 if not found;                              *
248  *        *p_n_pos = number of the searched element if found, else the    *
249  *        number of the first element that is larger than p_v_key.        *
250  **************************************************************************/
251 /* For those not familiar with binary search: n_lbound is the leftmost item that it
252  could be, n_rbound the rightmost item that it could be.  We examine the item
253  halfway between n_lbound and n_rbound, and that tells us either that we can increase
254  n_lbound, or decrease n_rbound, or that we have found it, or if n_lbound <= n_rbound that
255  there are no possible items, and we have not found it. With each examination we
256  cut the number of possible items it could be by one more than half rounded down,
257  or we find it. */
258 inline  int bin_search (
259               const void * p_v_key, /* Key to search for.                   */
260               const void * p_v_base,/* First item in the array.             */
261               int       p_n_num,    /* Number of items in the array.        */
262               int       p_n_width,  /* Item size in the array.
263                                        searched. Lest the reader be
264                                        confused, note that this is crafted
265                                        as a general function, and when it
266                                        is applied specifically to the array
267                                        of item headers in a node, p_n_width
268                                        is actually the item header size not
269                                        the item size.                      */
270               int     * p_n_pos     /* Number of the searched for element. */
271             ) {
272     int   n_rbound, n_lbound, n_j;
273
274    for ( n_j = ((n_rbound = p_n_num - 1) + (n_lbound = 0))/2; n_lbound <= n_rbound; n_j = (n_rbound + n_lbound)/2 )
275      switch( COMP_KEYS((struct key *)((char * )p_v_base + n_j * p_n_width), (struct cpu_key *)p_v_key) )  {
276      case -1: n_lbound = n_j + 1; continue;
277      case  1: n_rbound = n_j - 1; continue;
278      case  0: *p_n_pos = n_j;     return ITEM_FOUND; /* Key found in the array.  */
279         }
280
281     /* bin_search did not find given key, it returns position of key,
282         that is minimal and greater than the given one. */
283     *p_n_pos = n_lbound;
284     return ITEM_NOT_FOUND;
285 }
286
287 #ifdef CONFIG_REISERFS_CHECK
288 extern struct tree_balance * cur_tb;
289 #endif
290
291
292
293 /* Minimal possible key. It is never in the tree. */
294 const struct key  MIN_KEY = {0, 0, {{0, 0},}};
295
296 /* Maximal possible key. It is never in the tree. */
297 const struct key  MAX_KEY = {0xffffffff, 0xffffffff, {{0xffffffff, 0xffffffff},}};
298
299
300 /* Get delimiting key of the buffer by looking for it in the buffers in the path, starting from the bottom
301    of the path, and going upwards.  We must check the path's validity at each step.  If the key is not in
302    the path, there is no delimiting key in the tree (buffer is first or last buffer in tree), and in this
303    case we return a special key, either MIN_KEY or MAX_KEY. */
304 inline  const struct  key * get_lkey  (
305                         const struct path         * p_s_chk_path,
306                         const struct super_block  * p_s_sb
307                       ) {
308   int                   n_position, n_path_offset = p_s_chk_path->path_length;
309   struct buffer_head  * p_s_parent;
310   
311   RFALSE( n_path_offset < FIRST_PATH_ELEMENT_OFFSET, 
312           "PAP-5010: invalid offset in the path");
313
314   /* While not higher in path than first element. */
315   while ( n_path_offset-- > FIRST_PATH_ELEMENT_OFFSET ) {
316
317     RFALSE( ! buffer_uptodate(PATH_OFFSET_PBUFFER(p_s_chk_path, n_path_offset)),
318             "PAP-5020: parent is not uptodate");
319
320     /* Parent at the path is not in the tree now. */
321     if ( ! B_IS_IN_TREE(p_s_parent = PATH_OFFSET_PBUFFER(p_s_chk_path, n_path_offset)) )
322       return &MAX_KEY;
323     /* Check whether position in the parent is correct. */
324     if ( (n_position = PATH_OFFSET_POSITION(p_s_chk_path, n_path_offset)) > B_NR_ITEMS(p_s_parent) )
325        return &MAX_KEY;
326     /* Check whether parent at the path really points to the child. */
327     if ( B_N_CHILD_NUM(p_s_parent, n_position) !=
328          PATH_OFFSET_PBUFFER(p_s_chk_path, n_path_offset + 1)->b_blocknr )
329       return &MAX_KEY;
330     /* Return delimiting key if position in the parent is not equal to zero. */
331     if ( n_position )
332       return B_N_PDELIM_KEY(p_s_parent, n_position - 1);
333   }
334   /* Return MIN_KEY if we are in the root of the buffer tree. */
335   if ( PATH_OFFSET_PBUFFER(p_s_chk_path, FIRST_PATH_ELEMENT_OFFSET)->b_blocknr ==
336        SB_ROOT_BLOCK (p_s_sb) )
337     return &MIN_KEY;
338   return  &MAX_KEY;
339 }
340
341
342 /* Get delimiting key of the buffer at the path and its right neighbor. */
343 inline  const struct  key * get_rkey  (
344                         const struct path         * p_s_chk_path,
345                         const struct super_block  * p_s_sb
346                       ) {
347   int                   n_position,
348                         n_path_offset = p_s_chk_path->path_length;
349   struct buffer_head  * p_s_parent;
350
351   RFALSE( n_path_offset < FIRST_PATH_ELEMENT_OFFSET,
352           "PAP-5030: invalid offset in the path");
353
354   while ( n_path_offset-- > FIRST_PATH_ELEMENT_OFFSET ) {
355
356     RFALSE( ! buffer_uptodate(PATH_OFFSET_PBUFFER(p_s_chk_path, n_path_offset)),
357             "PAP-5040: parent is not uptodate");
358
359     /* Parent at the path is not in the tree now. */
360     if ( ! B_IS_IN_TREE(p_s_parent = PATH_OFFSET_PBUFFER(p_s_chk_path, n_path_offset)) )
361       return &MIN_KEY;
362     /* Check whether position in the parent is correct. */
363     if ( (n_position = PATH_OFFSET_POSITION(p_s_chk_path, n_path_offset)) > B_NR_ITEMS(p_s_parent) )
364       return &MIN_KEY;
365     /* Check whether parent at the path really points to the child. */
366     if ( B_N_CHILD_NUM(p_s_parent, n_position) !=
367                                         PATH_OFFSET_PBUFFER(p_s_chk_path, n_path_offset + 1)->b_blocknr )
368       return &MIN_KEY;
369     /* Return delimiting key if position in the parent is not the last one. */
370     if ( n_position != B_NR_ITEMS(p_s_parent) )
371       return B_N_PDELIM_KEY(p_s_parent, n_position);
372   }
373   /* Return MAX_KEY if we are in the root of the buffer tree. */
374   if ( PATH_OFFSET_PBUFFER(p_s_chk_path, FIRST_PATH_ELEMENT_OFFSET)->b_blocknr ==
375        SB_ROOT_BLOCK (p_s_sb) )
376     return &MAX_KEY;
377   return  &MIN_KEY;
378 }
379
380
381 /* Check whether a key is contained in the tree rooted from a buffer at a path. */
382 /* This works by looking at the left and right delimiting keys for the buffer in the last path_element in
383    the path.  These delimiting keys are stored at least one level above that buffer in the tree. If the
384    buffer is the first or last node in the tree order then one of the delimiting keys may be absent, and in
385    this case get_lkey and get_rkey return a special key which is MIN_KEY or MAX_KEY. */
386 static  inline  int key_in_buffer (
387                       struct path         * p_s_chk_path, /* Path which should be checked.  */
388                       const struct cpu_key      * p_s_key,      /* Key which should be checked.   */
389                       struct super_block  * p_s_sb        /* Super block pointer.           */
390                       ) {
391
392   RFALSE( ! p_s_key || p_s_chk_path->path_length < FIRST_PATH_ELEMENT_OFFSET ||
393           p_s_chk_path->path_length > MAX_HEIGHT,
394           "PAP-5050: pointer to the key(%p) is NULL or invalid path length(%d)",
395           p_s_key, p_s_chk_path->path_length);
396   RFALSE( !PATH_PLAST_BUFFER(p_s_chk_path)->b_bdev,
397           "PAP-5060: device must not be NODEV");
398
399   if ( COMP_KEYS(get_lkey(p_s_chk_path, p_s_sb), p_s_key) == 1 )
400     /* left delimiting key is bigger, that the key we look for */
401     return 0;
402   //  if ( COMP_KEYS(p_s_key, get_rkey(p_s_chk_path, p_s_sb)) != -1 )
403   if ( COMP_KEYS(get_rkey(p_s_chk_path, p_s_sb), p_s_key) != 1 )
404     /* p_s_key must be less than right delimitiing key */
405     return 0;
406   return 1;
407 }
408
409
410 inline void decrement_bcount(
411               struct buffer_head  * p_s_bh
412             ) { 
413   if ( p_s_bh ) {
414     if ( atomic_read (&(p_s_bh->b_count)) ) {
415       put_bh(p_s_bh) ;
416       return;
417     }
418     reiserfs_panic(NULL, "PAP-5070: decrement_bcount: trying to free free buffer %b", p_s_bh);
419   }
420 }
421
422
423 /* Decrement b_count field of the all buffers in the path. */
424 void decrement_counters_in_path (
425               struct path * p_s_search_path
426             ) {
427   int n_path_offset = p_s_search_path->path_length;
428
429   RFALSE( n_path_offset < ILLEGAL_PATH_ELEMENT_OFFSET ||
430           n_path_offset > EXTENDED_MAX_HEIGHT - 1,
431           "PAP-5080: invalid path offset of %d", n_path_offset);
432
433   while ( n_path_offset > ILLEGAL_PATH_ELEMENT_OFFSET ) {
434     struct buffer_head * bh;
435
436     bh = PATH_OFFSET_PBUFFER(p_s_search_path, n_path_offset--);
437     decrement_bcount (bh);
438   }
439   p_s_search_path->path_length = ILLEGAL_PATH_ELEMENT_OFFSET;
440 }
441
442
443 int reiserfs_check_path(struct path *p) {
444   RFALSE( p->path_length != ILLEGAL_PATH_ELEMENT_OFFSET,
445           "path not properly relsed") ;
446   return 0 ;
447 }
448
449
450 /* Release all buffers in the path. Restore dirty bits clean
451 ** when preparing the buffer for the log
452 **
453 ** only called from fix_nodes()
454 */
455 void  pathrelse_and_restore (
456         struct super_block *s, 
457         struct path * p_s_search_path
458       ) {
459   int n_path_offset = p_s_search_path->path_length;
460
461   RFALSE( n_path_offset < ILLEGAL_PATH_ELEMENT_OFFSET, 
462           "clm-4000: invalid path offset");
463   
464   while ( n_path_offset > ILLEGAL_PATH_ELEMENT_OFFSET )  {
465     reiserfs_restore_prepared_buffer(s, PATH_OFFSET_PBUFFER(p_s_search_path, 
466                                      n_path_offset));
467     brelse(PATH_OFFSET_PBUFFER(p_s_search_path, n_path_offset--));
468   }
469   p_s_search_path->path_length = ILLEGAL_PATH_ELEMENT_OFFSET;
470 }
471
472 /* Release all buffers in the path. */
473 void  pathrelse (
474         struct path * p_s_search_path
475       ) {
476   int n_path_offset = p_s_search_path->path_length;
477
478   RFALSE( n_path_offset < ILLEGAL_PATH_ELEMENT_OFFSET,
479           "PAP-5090: invalid path offset");
480   
481   while ( n_path_offset > ILLEGAL_PATH_ELEMENT_OFFSET )  
482     brelse(PATH_OFFSET_PBUFFER(p_s_search_path, n_path_offset--));
483
484   p_s_search_path->path_length = ILLEGAL_PATH_ELEMENT_OFFSET;
485 }
486
487
488
489 static int is_leaf (char * buf, int blocksize, struct buffer_head * bh)
490 {
491     struct block_head * blkh;
492     struct item_head * ih;
493     int used_space;
494     int prev_location;
495     int i;
496     int nr;
497
498     blkh = (struct block_head *)buf;
499     if ( blkh_level(blkh) != DISK_LEAF_NODE_LEVEL) {
500         reiserfs_warning (NULL, "is_leaf: this should be caught earlier");
501         return 0;
502     }
503
504     nr = blkh_nr_item(blkh);
505     if (nr < 1 || nr > ((blocksize - BLKH_SIZE) / (IH_SIZE + MIN_ITEM_LEN))) {
506         /* item number is too big or too small */
507         reiserfs_warning (NULL, "is_leaf: nr_item seems wrong: %z", bh);
508         return 0;
509     }
510     ih = (struct item_head *)(buf + BLKH_SIZE) + nr - 1;
511     used_space = BLKH_SIZE + IH_SIZE * nr + (blocksize - ih_location (ih));
512     if (used_space != blocksize - blkh_free_space(blkh)) {
513         /* free space does not match to calculated amount of use space */
514         reiserfs_warning (NULL, "is_leaf: free space seems wrong: %z", bh);
515         return 0;
516     }
517
518     // FIXME: it is_leaf will hit performance too much - we may have
519     // return 1 here
520
521     /* check tables of item heads */
522     ih = (struct item_head *)(buf + BLKH_SIZE);
523     prev_location = blocksize;
524     for (i = 0; i < nr; i ++, ih ++) {
525         if ( le_ih_k_type(ih) == TYPE_ANY) {
526             reiserfs_warning (NULL, "is_leaf: wrong item type for item %h",ih);
527             return 0;
528         }
529         if (ih_location (ih) >= blocksize || ih_location (ih) < IH_SIZE * nr) {
530             reiserfs_warning (NULL, "is_leaf: item location seems wrong: %h", ih);
531             return 0;
532         }
533         if (ih_item_len (ih) < 1 || ih_item_len (ih) > MAX_ITEM_LEN (blocksize)) {
534             reiserfs_warning (NULL, "is_leaf: item length seems wrong: %h", ih);
535             return 0;
536         }
537         if (prev_location - ih_location (ih) != ih_item_len (ih)) {
538             reiserfs_warning (NULL, "is_leaf: item location seems wrong (second one): %h", ih);
539             return 0;
540         }
541         prev_location = ih_location (ih);
542     }
543
544     // one may imagine much more checks
545     return 1;
546 }
547
548
549 /* returns 1 if buf looks like an internal node, 0 otherwise */
550 static int is_internal (char * buf, int blocksize, struct buffer_head * bh)
551 {
552     struct block_head * blkh;
553     int nr;
554     int used_space;
555
556     blkh = (struct block_head *)buf;
557     nr = blkh_level(blkh);
558     if (nr <= DISK_LEAF_NODE_LEVEL || nr > MAX_HEIGHT) {
559         /* this level is not possible for internal nodes */
560         reiserfs_warning (NULL, "is_internal: this should be caught earlier");
561         return 0;
562     }
563     
564     nr = blkh_nr_item(blkh);
565     if (nr > (blocksize - BLKH_SIZE - DC_SIZE) / (KEY_SIZE + DC_SIZE)) {
566         /* for internal which is not root we might check min number of keys */
567         reiserfs_warning (NULL, "is_internal: number of key seems wrong: %z", bh);
568         return 0;
569     }
570
571     used_space = BLKH_SIZE + KEY_SIZE * nr + DC_SIZE * (nr + 1);
572     if (used_space != blocksize - blkh_free_space(blkh)) {
573         reiserfs_warning (NULL, "is_internal: free space seems wrong: %z", bh);
574         return 0;
575     }
576
577     // one may imagine much more checks
578     return 1;
579 }
580
581
582 // make sure that bh contains formatted node of reiserfs tree of
583 // 'level'-th level
584 static int is_tree_node (struct buffer_head * bh, int level)
585 {
586     if (B_LEVEL (bh) != level) {
587         reiserfs_warning (NULL, "is_tree_node: node level %d does not match to the expected one %d",
588                 B_LEVEL (bh), level);
589         return 0;
590     }
591     if (level == DISK_LEAF_NODE_LEVEL)
592         return is_leaf (bh->b_data, bh->b_size, bh);
593
594     return is_internal (bh->b_data, bh->b_size, bh);
595 }
596
597
598
599 #ifdef SEARCH_BY_KEY_READA
600
601 /* The function is NOT SCHEDULE-SAFE! */
602 static void search_by_key_reada (struct super_block * s, int blocknr)
603 {
604     struct buffer_head * bh;
605   
606     if (blocknr == 0)
607         return;
608
609     bh = sb_getblk (s, blocknr);
610   
611     if (!buffer_uptodate (bh)) {
612         ll_rw_block (READA, 1, &bh);
613     }
614     bh->b_count --;
615 }
616
617 #endif
618
619 /**************************************************************************
620  * Algorithm   SearchByKey                                                *
621  *             look for item in the Disk S+Tree by its key                *
622  * Input:  p_s_sb   -  super block                                        *
623  *         p_s_key  - pointer to the key to search                        *
624  * Output: ITEM_FOUND, ITEM_NOT_FOUND or IO_ERROR                         *
625  *         p_s_search_path - path from the root to the needed leaf        *
626  **************************************************************************/
627
628 /* This function fills up the path from the root to the leaf as it
629    descends the tree looking for the key.  It uses reiserfs_bread to
630    try to find buffers in the cache given their block number.  If it
631    does not find them in the cache it reads them from disk.  For each
632    node search_by_key finds using reiserfs_bread it then uses
633    bin_search to look through that node.  bin_search will find the
634    position of the block_number of the next node if it is looking
635    through an internal node.  If it is looking through a leaf node
636    bin_search will find the position of the item which has key either
637    equal to given key, or which is the maximal key less than the given
638    key.  search_by_key returns a path that must be checked for the
639    correctness of the top of the path but need not be checked for the
640    correctness of the bottom of the path */
641 /* The function is NOT SCHEDULE-SAFE! */
642 int search_by_key (struct super_block * p_s_sb,
643                    const struct cpu_key * p_s_key, /* Key to search. */
644                    struct path * p_s_search_path, /* This structure was
645                                                      allocated and initialized
646                                                      by the calling
647                                                      function. It is filled up
648                                                      by this function.  */
649                    int n_stop_level /* How far down the tree to search. To
650                                        stop at leaf level - set to
651                                        DISK_LEAF_NODE_LEVEL */
652     ) {
653     int  n_block_number;
654     int  expected_level;
655     struct buffer_head  *       p_s_bh;
656     struct path_element *       p_s_last_element;
657     int                         n_node_level, n_retval;
658     int                         right_neighbor_of_leaf_node;
659     int                         fs_gen;
660
661 #ifdef CONFIG_REISERFS_CHECK
662     int n_repeat_counter = 0;
663 #endif
664     
665     PROC_INFO_INC( p_s_sb, search_by_key );
666     
667     /* As we add each node to a path we increase its count.  This means that
668        we must be careful to release all nodes in a path before we either
669        discard the path struct or re-use the path struct, as we do here. */
670
671     decrement_counters_in_path(p_s_search_path);
672
673     right_neighbor_of_leaf_node = 0;
674
675     /* With each iteration of this loop we search through the items in the
676        current node, and calculate the next current node(next path element)
677        for the next iteration of this loop.. */
678     n_block_number = SB_ROOT_BLOCK (p_s_sb);
679     expected_level = -1;
680     while ( 1 ) {
681
682 #ifdef CONFIG_REISERFS_CHECK
683         if ( !(++n_repeat_counter % 50000) )
684             reiserfs_warning (p_s_sb, "PAP-5100: search_by_key: %s:"
685                               "there were %d iterations of while loop "
686                               "looking for key %K",
687                               current->comm, n_repeat_counter, p_s_key);
688 #endif
689
690         /* prep path to have another element added to it. */
691         p_s_last_element = PATH_OFFSET_PELEMENT(p_s_search_path, ++p_s_search_path->path_length);
692         fs_gen = get_generation (p_s_sb);
693
694 #ifdef SEARCH_BY_KEY_READA
695         /* schedule read of right neighbor */
696         search_by_key_reada (p_s_sb, right_neighbor_of_leaf_node);
697 #endif
698
699         /* Read the next tree node, and set the last element in the path to
700            have a pointer to it. */
701         if ( ! (p_s_bh = p_s_last_element->pe_buffer =
702                 sb_bread(p_s_sb, n_block_number)) ) {
703             p_s_search_path->path_length --;
704             pathrelse(p_s_search_path);
705             return IO_ERROR;
706         }
707         if (expected_level == -1)
708                 expected_level = SB_TREE_HEIGHT (p_s_sb);
709         expected_level --;
710
711         /* It is possible that schedule occurred. We must check whether the key
712            to search is still in the tree rooted from the current buffer. If
713            not then repeat search from the root. */
714         if ( fs_changed (fs_gen, p_s_sb) && 
715             (!B_IS_IN_TREE (p_s_bh) ||
716              B_LEVEL(p_s_bh) != expected_level ||
717              !key_in_buffer(p_s_search_path, p_s_key, p_s_sb))) {
718             PROC_INFO_INC( p_s_sb, search_by_key_fs_changed );
719             PROC_INFO_INC( p_s_sb, search_by_key_restarted );
720             PROC_INFO_INC( p_s_sb, sbk_restarted[ expected_level - 1 ] );
721             decrement_counters_in_path(p_s_search_path);
722             
723             /* Get the root block number so that we can repeat the search
724                starting from the root. */
725             n_block_number = SB_ROOT_BLOCK (p_s_sb);
726             expected_level = -1;
727             right_neighbor_of_leaf_node = 0;
728             
729             /* repeat search from the root */
730             continue;
731         }
732
733         /* only check that the key is in the buffer if p_s_key is not
734            equal to the MAX_KEY. Latter case is only possible in
735            "finish_unfinished()" processing during mount. */
736         RFALSE( COMP_KEYS( &MAX_KEY, p_s_key ) && 
737                 ! key_in_buffer(p_s_search_path, p_s_key, p_s_sb),
738                 "PAP-5130: key is not in the buffer");
739 #ifdef CONFIG_REISERFS_CHECK
740         if ( cur_tb ) {
741             print_cur_tb ("5140");
742             reiserfs_panic(p_s_sb, "PAP-5140: search_by_key: schedule occurred in do_balance!");
743         }
744 #endif
745
746         // make sure, that the node contents look like a node of
747         // certain level
748         if (!is_tree_node (p_s_bh, expected_level)) {
749             reiserfs_warning (p_s_sb, "vs-5150: search_by_key: "
750                               "invalid format found in block %ld. Fsck?",
751                               p_s_bh->b_blocknr);
752             pathrelse (p_s_search_path);
753             return IO_ERROR;
754         }
755         
756         /* ok, we have acquired next formatted node in the tree */
757         n_node_level = B_LEVEL (p_s_bh);
758
759         PROC_INFO_BH_STAT( p_s_sb, p_s_bh, n_node_level - 1 );
760
761         RFALSE( n_node_level < n_stop_level,
762                 "vs-5152: tree level (%d) is less than stop level (%d)",
763                 n_node_level, n_stop_level);
764
765         n_retval = bin_search( p_s_key, B_N_PITEM_HEAD(p_s_bh, 0),
766                 B_NR_ITEMS(p_s_bh),
767                 ( n_node_level == DISK_LEAF_NODE_LEVEL ) ? IH_SIZE : KEY_SIZE,
768                 &(p_s_last_element->pe_position));
769         if (n_node_level == n_stop_level) {
770             return n_retval;
771         }
772
773         /* we are not in the stop level */
774         if (n_retval == ITEM_FOUND)
775             /* item has been found, so we choose the pointer which is to the right of the found one */
776             p_s_last_element->pe_position++;
777
778         /* if item was not found we choose the position which is to
779            the left of the found item. This requires no code,
780            bin_search did it already.*/
781
782         /* So we have chosen a position in the current node which is
783            an internal node.  Now we calculate child block number by
784            position in the node. */
785         n_block_number = B_N_CHILD_NUM(p_s_bh, p_s_last_element->pe_position);
786
787 #ifdef SEARCH_BY_KEY_READA
788         /* if we are going to read leaf node, then calculate its right neighbor if possible */
789         if (n_node_level == DISK_LEAF_NODE_LEVEL + 1 && p_s_last_element->pe_position < B_NR_ITEMS (p_s_bh))
790             right_neighbor_of_leaf_node = B_N_CHILD_NUM(p_s_bh, p_s_last_element->pe_position + 1);
791 #endif
792     }
793 }
794
795
796 /* Form the path to an item and position in this item which contains
797    file byte defined by p_s_key. If there is no such item
798    corresponding to the key, we point the path to the item with
799    maximal key less than p_s_key, and *p_n_pos_in_item is set to one
800    past the last entry/byte in the item.  If searching for entry in a
801    directory item, and it is not found, *p_n_pos_in_item is set to one
802    entry more than the entry with maximal key which is less than the
803    sought key.
804
805    Note that if there is no entry in this same node which is one more,
806    then we point to an imaginary entry.  for direct items, the
807    position is in units of bytes, for indirect items the position is
808    in units of blocknr entries, for directory items the position is in
809    units of directory entries.  */
810
811 /* The function is NOT SCHEDULE-SAFE! */
812 int search_for_position_by_key (struct super_block  * p_s_sb,         /* Pointer to the super block.          */
813                                 const struct cpu_key  * p_cpu_key,      /* Key to search (cpu variable)         */
814                                 struct path         * p_s_search_path /* Filled up by this function.          */
815     ) {
816     struct item_head    * p_le_ih; /* pointer to on-disk structure */
817     int                   n_blk_size;
818     loff_t item_offset, offset;
819     struct reiserfs_dir_entry de;
820     int retval;
821
822     /* If searching for directory entry. */
823     if ( is_direntry_cpu_key (p_cpu_key) )
824         return  search_by_entry_key (p_s_sb, p_cpu_key, p_s_search_path, &de);
825
826     /* If not searching for directory entry. */
827     
828     /* If item is found. */
829     retval = search_item (p_s_sb, p_cpu_key, p_s_search_path);
830     if (retval == IO_ERROR)
831         return retval;
832     if ( retval == ITEM_FOUND )  {
833
834         RFALSE( ! ih_item_len(
835                 B_N_PITEM_HEAD(PATH_PLAST_BUFFER(p_s_search_path),
836                                PATH_LAST_POSITION(p_s_search_path))),
837                 "PAP-5165: item length equals zero");
838
839         pos_in_item(p_s_search_path) = 0;
840         return POSITION_FOUND;
841     }
842
843     RFALSE( ! PATH_LAST_POSITION(p_s_search_path),
844             "PAP-5170: position equals zero");
845
846     /* Item is not found. Set path to the previous item. */
847     p_le_ih = B_N_PITEM_HEAD(PATH_PLAST_BUFFER(p_s_search_path), --PATH_LAST_POSITION(p_s_search_path));
848     n_blk_size = p_s_sb->s_blocksize;
849
850     if (comp_short_keys (&(p_le_ih->ih_key), p_cpu_key)) {
851         return FILE_NOT_FOUND;
852     }
853
854     // FIXME: quite ugly this far
855
856     item_offset = le_ih_k_offset (p_le_ih);
857     offset = cpu_key_k_offset (p_cpu_key);
858
859     /* Needed byte is contained in the item pointed to by the path.*/
860     if (item_offset <= offset &&
861         item_offset + op_bytes_number (p_le_ih, n_blk_size) > offset) {
862         pos_in_item (p_s_search_path) = offset - item_offset;
863         if ( is_indirect_le_ih(p_le_ih) ) {
864             pos_in_item (p_s_search_path) /= n_blk_size;
865         }
866         return POSITION_FOUND;
867     }
868
869     /* Needed byte is not contained in the item pointed to by the
870      path. Set pos_in_item out of the item. */
871     if ( is_indirect_le_ih (p_le_ih) )
872         pos_in_item (p_s_search_path) = ih_item_len(p_le_ih) / UNFM_P_SIZE;
873     else
874         pos_in_item (p_s_search_path) = ih_item_len( p_le_ih );
875   
876     return POSITION_NOT_FOUND;
877 }
878
879
880 /* Compare given item and item pointed to by the path. */
881 int comp_items (const struct item_head * stored_ih, const struct path * p_s_path)
882 {
883     struct buffer_head  * p_s_bh;
884     struct item_head    * ih;
885
886     /* Last buffer at the path is not in the tree. */
887     if ( ! B_IS_IN_TREE(p_s_bh = PATH_PLAST_BUFFER(p_s_path)) )
888         return 1;
889
890     /* Last path position is invalid. */
891     if ( PATH_LAST_POSITION(p_s_path) >= B_NR_ITEMS(p_s_bh) )
892         return 1;
893
894     /* we need only to know, whether it is the same item */
895     ih = get_ih (p_s_path);
896     return memcmp (stored_ih, ih, IH_SIZE);
897 }
898
899
900 /* unformatted nodes are not logged anymore, ever.  This is safe
901 ** now
902 */
903 #define held_by_others(bh) (atomic_read(&(bh)->b_count) > 1)
904
905 // block can not be forgotten as it is in I/O or held by someone
906 #define block_in_use(bh) (buffer_locked(bh) || (held_by_others(bh)))
907
908
909
910 // prepare for delete or cut of direct item
911 static inline int prepare_for_direct_item (struct path * path,
912                                            struct item_head * le_ih,
913                                            struct inode * inode,
914                                            loff_t new_file_length,
915                                            int * cut_size)
916 {
917     loff_t round_len;
918
919
920     if ( new_file_length == max_reiserfs_offset (inode) ) {
921         /* item has to be deleted */
922         *cut_size = -(IH_SIZE + ih_item_len(le_ih));
923         return M_DELETE;
924     }
925         
926     // new file gets truncated
927     if (get_inode_item_key_version (inode) == KEY_FORMAT_3_6) {
928         // 
929         round_len = ROUND_UP (new_file_length); 
930         /* this was n_new_file_length < le_ih ... */
931         if ( round_len < le_ih_k_offset (le_ih) )  {
932             *cut_size = -(IH_SIZE + ih_item_len(le_ih));
933             return M_DELETE; /* Delete this item. */
934         }
935         /* Calculate first position and size for cutting from item. */
936         pos_in_item (path) = round_len - (le_ih_k_offset (le_ih) - 1);
937         *cut_size = -(ih_item_len(le_ih) - pos_in_item(path));
938         
939         return M_CUT; /* Cut from this item. */
940     }
941
942
943     // old file: items may have any length
944
945     if ( new_file_length < le_ih_k_offset (le_ih) )  {
946         *cut_size = -(IH_SIZE + ih_item_len(le_ih));
947         return M_DELETE; /* Delete this item. */
948     }
949     /* Calculate first position and size for cutting from item. */
950     *cut_size = -(ih_item_len(le_ih) -
951                       (pos_in_item (path) = new_file_length + 1 - le_ih_k_offset (le_ih)));
952     return M_CUT; /* Cut from this item. */
953 }
954
955
956 static inline int prepare_for_direntry_item (struct path * path,
957                                              struct item_head * le_ih,
958                                              struct inode * inode,
959                                              loff_t new_file_length,
960                                              int * cut_size)
961 {
962     if (le_ih_k_offset (le_ih) == DOT_OFFSET && 
963         new_file_length == max_reiserfs_offset (inode)) {
964         RFALSE( ih_entry_count (le_ih) != 2,
965                 "PAP-5220: incorrect empty directory item (%h)", le_ih);
966         *cut_size = -(IH_SIZE + ih_item_len(le_ih));
967         return M_DELETE; /* Delete the directory item containing "." and ".." entry. */
968     }
969     
970     if ( ih_entry_count (le_ih) == 1 )  {
971         /* Delete the directory item such as there is one record only
972            in this item*/
973         *cut_size = -(IH_SIZE + ih_item_len(le_ih));
974         return M_DELETE;
975     }
976     
977     /* Cut one record from the directory item. */
978     *cut_size = -(DEH_SIZE + entry_length (get_last_bh (path), le_ih, pos_in_item (path)));
979     return M_CUT; 
980 }
981
982
983 /*  If the path points to a directory or direct item, calculate mode and the size cut, for balance.
984     If the path points to an indirect item, remove some number of its unformatted nodes.
985     In case of file truncate calculate whether this item must be deleted/truncated or last
986     unformatted node of this item will be converted to a direct item.
987     This function returns a determination of what balance mode the calling function should employ. */
988 static char  prepare_for_delete_or_cut(
989                                        struct reiserfs_transaction_handle *th, 
990                                        struct inode * inode,
991                                        struct path         * p_s_path,
992                                        const struct cpu_key      * p_s_item_key,
993                                        int                 * p_n_removed,      /* Number of unformatted nodes which were removed
994                                                                                   from end of the file. */
995                                        int                 * p_n_cut_size,
996                                        unsigned long long    n_new_file_length /* MAX_KEY_OFFSET in case of delete. */
997     ) {
998     struct super_block  * p_s_sb = inode->i_sb;
999     struct item_head    * p_le_ih = PATH_PITEM_HEAD(p_s_path);
1000     struct buffer_head  * p_s_bh = PATH_PLAST_BUFFER(p_s_path);
1001
1002     /* Stat_data item. */
1003     if ( is_statdata_le_ih (p_le_ih) ) {
1004
1005         RFALSE( n_new_file_length != max_reiserfs_offset (inode),
1006                 "PAP-5210: mode must be M_DELETE");
1007
1008         *p_n_cut_size = -(IH_SIZE + ih_item_len(p_le_ih));
1009         return M_DELETE;
1010     }
1011
1012
1013     /* Directory item. */
1014     if ( is_direntry_le_ih (p_le_ih) )
1015         return prepare_for_direntry_item (p_s_path, p_le_ih, inode, n_new_file_length, p_n_cut_size);
1016
1017     /* Direct item. */
1018     if ( is_direct_le_ih (p_le_ih) )
1019         return prepare_for_direct_item (p_s_path, p_le_ih, inode, n_new_file_length, p_n_cut_size);
1020
1021
1022     /* Case of an indirect item. */
1023     {
1024         int                   n_unfm_number,    /* Number of the item unformatted nodes. */
1025             n_counter,
1026             n_blk_size;
1027         __u32               * p_n_unfm_pointer; /* Pointer to the unformatted node number. */
1028         __u32 tmp;
1029         struct item_head      s_ih;           /* Item header. */
1030         char                  c_mode;           /* Returned mode of the balance. */
1031         int need_research;
1032
1033
1034         n_blk_size = p_s_sb->s_blocksize;
1035
1036         /* Search for the needed object indirect item until there are no unformatted nodes to be removed. */
1037         do  {
1038             need_research = 0;
1039             p_s_bh = PATH_PLAST_BUFFER(p_s_path);
1040             /* Copy indirect item header to a temp variable. */
1041             copy_item_head(&s_ih, PATH_PITEM_HEAD(p_s_path));
1042             /* Calculate number of unformatted nodes in this item. */
1043             n_unfm_number = I_UNFM_NUM(&s_ih);
1044
1045             RFALSE( ! is_indirect_le_ih(&s_ih) || ! n_unfm_number ||
1046                     pos_in_item (p_s_path) + 1 !=  n_unfm_number,
1047                     "PAP-5240: invalid item %h "
1048                     "n_unfm_number = %d *p_n_pos_in_item = %d", 
1049                     &s_ih, n_unfm_number, pos_in_item (p_s_path));
1050
1051             /* Calculate balance mode and position in the item to remove unformatted nodes. */
1052             if ( n_new_file_length == max_reiserfs_offset (inode) ) {/* Case of delete. */
1053                 pos_in_item (p_s_path) = 0;
1054                 *p_n_cut_size = -(IH_SIZE + ih_item_len(&s_ih));
1055                 c_mode = M_DELETE;
1056             }
1057             else  { /* Case of truncate. */
1058                 if ( n_new_file_length < le_ih_k_offset (&s_ih) )  {
1059                     pos_in_item (p_s_path) = 0;
1060                     *p_n_cut_size = -(IH_SIZE + ih_item_len(&s_ih));
1061                     c_mode = M_DELETE; /* Delete this item. */
1062                 }
1063                 else  {
1064                     /* indirect item must be truncated starting from *p_n_pos_in_item-th position */
1065                     pos_in_item (p_s_path) = (n_new_file_length + n_blk_size - le_ih_k_offset (&s_ih) ) >> p_s_sb->s_blocksize_bits;
1066
1067                     RFALSE( pos_in_item (p_s_path) > n_unfm_number,
1068                             "PAP-5250: invalid position in the item");
1069
1070                     /* Either convert last unformatted node of indirect item to direct item or increase
1071                        its free space.  */
1072                     if ( pos_in_item (p_s_path) == n_unfm_number )  {
1073                         *p_n_cut_size = 0; /* Nothing to cut. */
1074                         return M_CONVERT; /* Maybe convert last unformatted node to the direct item. */
1075                     }
1076                     /* Calculate size to cut. */
1077                     *p_n_cut_size = -(ih_item_len(&s_ih) - pos_in_item(p_s_path) * UNFM_P_SIZE);
1078
1079                     c_mode = M_CUT;     /* Cut from this indirect item. */
1080                 }
1081             }
1082
1083             RFALSE( n_unfm_number <= pos_in_item (p_s_path),
1084                     "PAP-5260: invalid position in the indirect item");
1085
1086             /* pointers to be cut */
1087             n_unfm_number -= pos_in_item (p_s_path);
1088             /* Set pointer to the last unformatted node pointer that is to be cut. */
1089             p_n_unfm_pointer = (__u32 *)B_I_PITEM(p_s_bh, &s_ih) + I_UNFM_NUM(&s_ih) - 1 - *p_n_removed;
1090
1091
1092             /* We go through the unformatted nodes pointers of the indirect
1093                item and look for the unformatted nodes in the cache. If we
1094                found some of them we free it, zero corresponding indirect item
1095                entry and log buffer containing that indirect item. For this we
1096                need to prepare last path element for logging. If some
1097                unformatted node has b_count > 1 we must not free this
1098                unformatted node since it is in use. */
1099             reiserfs_prepare_for_journal(p_s_sb, p_s_bh, 1);
1100             // note: path could be changed, first line in for loop takes care
1101             // of it
1102
1103             for (n_counter = *p_n_removed;
1104                  n_counter < n_unfm_number; n_counter++, p_n_unfm_pointer-- ) {
1105
1106                 cond_resched();
1107                 if (item_moved (&s_ih, p_s_path)) {
1108                     need_research = 1 ;
1109                     break;
1110                 }
1111                 RFALSE( p_n_unfm_pointer < (__u32 *)B_I_PITEM(p_s_bh, &s_ih) ||
1112                         p_n_unfm_pointer > (__u32 *)B_I_PITEM(p_s_bh, &s_ih) + I_UNFM_NUM(&s_ih) - 1,
1113                         "vs-5265: pointer out of range");
1114
1115                 /* Hole, nothing to remove. */
1116                 if ( ! get_block_num(p_n_unfm_pointer,0) )  {
1117                         (*p_n_removed)++;
1118                         continue;
1119                 }
1120
1121                 (*p_n_removed)++;
1122
1123                 tmp = get_block_num(p_n_unfm_pointer,0);
1124                 put_block_num(p_n_unfm_pointer, 0, 0);
1125                 journal_mark_dirty (th, p_s_sb, p_s_bh);
1126                 reiserfs_free_block(th, inode, tmp, 1);
1127                 if ( item_moved (&s_ih, p_s_path) )  {
1128                         need_research = 1;
1129                         break ;
1130                 }
1131             }
1132
1133             /* a trick.  If the buffer has been logged, this
1134             ** will do nothing.  If we've broken the loop without
1135             ** logging it, it will restore the buffer
1136             **
1137             */
1138             reiserfs_restore_prepared_buffer(p_s_sb, p_s_bh);
1139
1140             /* This loop can be optimized. */
1141         } while ( (*p_n_removed < n_unfm_number || need_research) &&
1142                   search_for_position_by_key(p_s_sb, p_s_item_key, p_s_path) == POSITION_FOUND );
1143
1144         RFALSE( *p_n_removed < n_unfm_number, 
1145                 "PAP-5310: indirect item is not found");
1146         RFALSE( item_moved (&s_ih, p_s_path), 
1147                 "after while, comp failed, retry") ;
1148
1149         if (c_mode == M_CUT)
1150             pos_in_item (p_s_path) *= UNFM_P_SIZE;
1151         return c_mode;
1152     }
1153 }
1154
1155 /* Calculate number of bytes which will be deleted or cut during balance */
1156 int calc_deleted_bytes_number(
1157     struct  tree_balance  * p_s_tb,
1158     char                    c_mode
1159     ) {
1160     int                     n_del_size;
1161     struct  item_head     * p_le_ih = PATH_PITEM_HEAD(p_s_tb->tb_path);
1162
1163     if ( is_statdata_le_ih (p_le_ih) )
1164         return 0;
1165
1166     n_del_size = ( c_mode == M_DELETE ) ? ih_item_len(p_le_ih) : -p_s_tb->insert_size[0];
1167     if ( is_direntry_le_ih (p_le_ih) ) {
1168         // return EMPTY_DIR_SIZE; /* We delete emty directoris only. */
1169         // we can't use EMPTY_DIR_SIZE, as old format dirs have a different
1170         // empty size.  ick. FIXME, is this right?
1171         //
1172         return n_del_size ;
1173     }
1174
1175     if ( is_indirect_le_ih (p_le_ih) )
1176         n_del_size = (n_del_size/UNFM_P_SIZE)*
1177           (PATH_PLAST_BUFFER(p_s_tb->tb_path)->b_size);// - get_ih_free_space (p_le_ih);
1178     return n_del_size;
1179 }
1180
1181 static void init_tb_struct(
1182     struct reiserfs_transaction_handle *th,
1183     struct tree_balance * p_s_tb,
1184     struct super_block  * p_s_sb,
1185     struct path         * p_s_path,
1186     int                   n_size
1187     ) {
1188     memset (p_s_tb,'\0',sizeof(struct tree_balance));
1189     p_s_tb->transaction_handle = th ;
1190     p_s_tb->tb_sb = p_s_sb;
1191     p_s_tb->tb_path = p_s_path;
1192     PATH_OFFSET_PBUFFER(p_s_path, ILLEGAL_PATH_ELEMENT_OFFSET) = NULL;
1193     PATH_OFFSET_POSITION(p_s_path, ILLEGAL_PATH_ELEMENT_OFFSET) = 0;
1194     p_s_tb->insert_size[0] = n_size;
1195 }
1196
1197
1198
1199 void padd_item (char * item, int total_length, int length)
1200 {
1201     int i;
1202
1203     for (i = total_length; i > length; )
1204         item [--i] = 0;
1205 }
1206
1207 #ifdef REISERQUOTA_DEBUG
1208 char key2type(struct key *ih)
1209 {
1210   if (is_direntry_le_key(2, ih))
1211     return 'd';
1212   if (is_direct_le_key(2, ih))
1213     return 'D';
1214   if (is_indirect_le_key(2, ih))
1215     return 'i';
1216   if (is_statdata_le_key(2, ih))
1217     return 's';
1218   return 'u';
1219 }
1220
1221 char head2type(struct item_head *ih)
1222 {
1223   if (is_direntry_le_ih(ih))
1224     return 'd';
1225   if (is_direct_le_ih(ih))
1226     return 'D';
1227   if (is_indirect_le_ih(ih))
1228     return 'i';
1229   if (is_statdata_le_ih(ih))
1230     return 's';
1231   return 'u';
1232 }
1233 #endif
1234
1235 /* Delete object item. */
1236 int reiserfs_delete_item (struct reiserfs_transaction_handle *th, 
1237                           struct path * p_s_path, /* Path to the deleted item. */
1238                           const struct cpu_key * p_s_item_key, /* Key to search for the deleted item.  */
1239                           struct inode * p_s_inode,/* inode is here just to update i_blocks and quotas */
1240                           struct buffer_head  * p_s_un_bh)    /* NULL or unformatted node pointer.    */
1241 {
1242     struct super_block * p_s_sb = p_s_inode->i_sb;
1243     struct tree_balance   s_del_balance;
1244     struct item_head      s_ih;
1245     struct item_head      *q_ih;
1246     int                   quota_cut_bytes;
1247     int                   n_ret_value,
1248         n_del_size,
1249         n_removed;
1250
1251 #ifdef CONFIG_REISERFS_CHECK
1252     char                  c_mode;
1253     int                 n_iter = 0;
1254 #endif
1255
1256     init_tb_struct(th, &s_del_balance, p_s_sb, p_s_path, 0/*size is unknown*/);
1257
1258     while ( 1 ) {
1259         n_removed = 0;
1260
1261 #ifdef CONFIG_REISERFS_CHECK
1262         n_iter++;
1263         c_mode =
1264 #endif
1265             prepare_for_delete_or_cut(th, p_s_inode, p_s_path, p_s_item_key, &n_removed, &n_del_size, max_reiserfs_offset (p_s_inode));
1266
1267         RFALSE( c_mode != M_DELETE, "PAP-5320: mode must be M_DELETE");
1268
1269         copy_item_head(&s_ih, PATH_PITEM_HEAD(p_s_path));
1270         s_del_balance.insert_size[0] = n_del_size;
1271
1272         n_ret_value = fix_nodes(M_DELETE, &s_del_balance, NULL, 0);
1273         if ( n_ret_value != REPEAT_SEARCH )
1274             break;
1275
1276         PROC_INFO_INC( p_s_sb, delete_item_restarted );
1277
1278         // file system changed, repeat search
1279         n_ret_value = search_for_position_by_key(p_s_sb, p_s_item_key, p_s_path);
1280         if (n_ret_value == IO_ERROR)
1281             break;
1282         if (n_ret_value == FILE_NOT_FOUND) {
1283             reiserfs_warning (p_s_sb, "vs-5340: reiserfs_delete_item: "
1284                               "no items of the file %K found", p_s_item_key);
1285             break;
1286         }
1287     } /* while (1) */
1288
1289     if ( n_ret_value != CARRY_ON ) {
1290         unfix_nodes(&s_del_balance);
1291         return 0;
1292     }
1293
1294     // reiserfs_delete_item returns item length when success
1295     n_ret_value = calc_deleted_bytes_number(&s_del_balance, M_DELETE);
1296     q_ih = get_ih(p_s_path) ;
1297     quota_cut_bytes = ih_item_len(q_ih) ;
1298
1299     /* hack so the quota code doesn't have to guess if the file
1300     ** has a tail.  On tail insert, we allocate quota for 1 unformatted node.
1301     ** We test the offset because the tail might have been
1302     ** split into multiple items, and we only want to decrement for
1303     ** the unfm node once
1304     */
1305     if (!S_ISLNK (p_s_inode->i_mode) && is_direct_le_ih(q_ih)) {
1306         if ((le_ih_k_offset(q_ih) & (p_s_sb->s_blocksize - 1)) == 1) {
1307             quota_cut_bytes = p_s_sb->s_blocksize + UNFM_P_SIZE;
1308         } else {
1309             quota_cut_bytes = 0 ;
1310         }
1311     }
1312
1313     if ( p_s_un_bh )  {
1314         int off;
1315         char *data ;
1316
1317         /* We are in direct2indirect conversion, so move tail contents
1318            to the unformatted node */
1319         /* note, we do the copy before preparing the buffer because we
1320         ** don't care about the contents of the unformatted node yet.
1321         ** the only thing we really care about is the direct item's data
1322         ** is in the unformatted node.
1323         **
1324         ** Otherwise, we would have to call reiserfs_prepare_for_journal on
1325         ** the unformatted node, which might schedule, meaning we'd have to
1326         ** loop all the way back up to the start of the while loop.
1327         **
1328         ** The unformatted node must be dirtied later on.  We can't be
1329         ** sure here if the entire tail has been deleted yet.
1330         **
1331         ** p_s_un_bh is from the page cache (all unformatted nodes are
1332         ** from the page cache) and might be a highmem page.  So, we
1333         ** can't use p_s_un_bh->b_data.
1334         ** -clm
1335         */
1336
1337         data = kmap_atomic(p_s_un_bh->b_page, KM_USER0);
1338         off = ((le_ih_k_offset (&s_ih) - 1) & (PAGE_CACHE_SIZE - 1));
1339         memcpy(data + off,
1340                B_I_PITEM(PATH_PLAST_BUFFER(p_s_path), &s_ih), n_ret_value);
1341         kunmap_atomic(data, KM_USER0);
1342     }
1343     /* Perform balancing after all resources have been collected at once. */ 
1344     do_balance(&s_del_balance, NULL, NULL, M_DELETE);
1345
1346 #ifdef REISERQUOTA_DEBUG
1347     reiserfs_debug (p_s_sb, "reiserquota delete_item(): freeing %u, id=%u type=%c", quota_cut_bytes, p_s_inode->i_uid, head2type(&s_ih));
1348 #endif
1349     DQUOT_FREE_SPACE_NODIRTY(p_s_inode, quota_cut_bytes);
1350
1351     /* Return deleted body length */
1352     return n_ret_value;
1353 }
1354
1355
1356 /* Summary Of Mechanisms For Handling Collisions Between Processes:
1357
1358  deletion of the body of the object is performed by iput(), with the
1359  result that if multiple processes are operating on a file, the
1360  deletion of the body of the file is deferred until the last process
1361  that has an open inode performs its iput().
1362
1363  writes and truncates are protected from collisions by use of
1364  semaphores.
1365
1366  creates, linking, and mknod are protected from collisions with other
1367  processes by making the reiserfs_add_entry() the last step in the
1368  creation, and then rolling back all changes if there was a collision.
1369  - Hans
1370 */
1371
1372
1373 /* this deletes item which never gets split */
1374 void reiserfs_delete_solid_item (struct reiserfs_transaction_handle *th,
1375                                  struct inode *inode,
1376                                  struct key * key)
1377 {
1378     struct tree_balance tb;
1379     INITIALIZE_PATH (path);
1380     int item_len = 0;
1381     int tb_init = 0 ;
1382     struct cpu_key cpu_key;
1383     int retval;
1384     int quota_cut_bytes = 0;
1385     
1386     le_key2cpu_key (&cpu_key, key);
1387     
1388     while (1) {
1389         retval = search_item (th->t_super, &cpu_key, &path);
1390         if (retval == IO_ERROR) {
1391             reiserfs_warning (th->t_super,
1392                               "vs-5350: reiserfs_delete_solid_item: "
1393                               "i/o failure occurred trying to delete %K",
1394                               &cpu_key);
1395             break;
1396         }
1397         if (retval != ITEM_FOUND) {
1398             pathrelse (&path);
1399             // No need for a warning, if there is just no free space to insert '..' item into the newly-created subdir
1400             if ( !( (unsigned long long) GET_HASH_VALUE (le_key_k_offset (le_key_version (key), key)) == 0 && \
1401                  (unsigned long long) GET_GENERATION_NUMBER (le_key_k_offset (le_key_version (key), key)) == 1 ) )
1402                 reiserfs_warning (th->t_super, "vs-5355: reiserfs_delete_solid_item: %k not found", key);
1403             break;
1404         }
1405         if (!tb_init) {
1406             tb_init = 1 ;
1407             item_len = ih_item_len( PATH_PITEM_HEAD(&path) );
1408             init_tb_struct (th, &tb, th->t_super, &path, - (IH_SIZE + item_len));
1409         }
1410         quota_cut_bytes = ih_item_len(PATH_PITEM_HEAD(&path)) ;
1411
1412         retval = fix_nodes (M_DELETE, &tb, NULL, 0);
1413         if (retval == REPEAT_SEARCH) {
1414             PROC_INFO_INC( th -> t_super, delete_solid_item_restarted );
1415             continue;
1416         }
1417
1418         if (retval == CARRY_ON) {
1419             do_balance (&tb, 0, 0, M_DELETE);
1420             if (inode) {        /* Should we count quota for item? (we don't count quotas for save-links) */
1421 #ifdef REISERQUOTA_DEBUG
1422                 reiserfs_debug (th->t_super, "reiserquota delete_solid_item(): freeing %u id=%u type=%c", quota_cut_bytes, inode->i_uid, key2type(key));
1423 #endif
1424                 DQUOT_FREE_SPACE_NODIRTY(inode, quota_cut_bytes);
1425             }
1426             break;
1427         }
1428
1429         // IO_ERROR, NO_DISK_SPACE, etc
1430         reiserfs_warning (th->t_super, "vs-5360: reiserfs_delete_solid_item: "
1431                           "could not delete %K due to fix_nodes failure", &cpu_key);
1432         unfix_nodes (&tb);
1433         break;
1434     }
1435
1436     reiserfs_check_path(&path) ;
1437 }
1438
1439
1440 void reiserfs_delete_object (struct reiserfs_transaction_handle *th, struct inode * inode)
1441 {
1442     inode->i_size = 0;
1443
1444     /* for directory this deletes item containing "." and ".." */
1445     reiserfs_do_truncate (th, inode, NULL, 0/*no timestamp updates*/);
1446     
1447 #if defined( USE_INODE_GENERATION_COUNTER )
1448     if( !old_format_only ( th -> t_super ) )
1449       {
1450        __u32 *inode_generation;
1451        
1452        inode_generation = 
1453          &REISERFS_SB(th -> t_super) -> s_rs -> s_inode_generation;
1454        *inode_generation = cpu_to_le32( le32_to_cpu( *inode_generation ) + 1 );
1455       }
1456 /* USE_INODE_GENERATION_COUNTER */
1457 #endif
1458     reiserfs_delete_solid_item (th, inode, INODE_PKEY (inode));
1459 }
1460
1461
1462 static int maybe_indirect_to_direct (struct reiserfs_transaction_handle *th, 
1463                               struct inode * p_s_inode,
1464                               struct page *page, 
1465                               struct path         * p_s_path,
1466                               const struct cpu_key      * p_s_item_key,
1467                               loff_t         n_new_file_size,
1468                               char                * p_c_mode
1469                               ) {
1470     struct super_block * p_s_sb = p_s_inode->i_sb;
1471     int n_block_size = p_s_sb->s_blocksize;
1472     int cut_bytes;
1473
1474     if (n_new_file_size != p_s_inode->i_size)
1475         BUG ();
1476
1477     /* the page being sent in could be NULL if there was an i/o error
1478     ** reading in the last block.  The user will hit problems trying to
1479     ** read the file, but for now we just skip the indirect2direct
1480     */
1481     if (atomic_read(&p_s_inode->i_count) > 1 || 
1482         !tail_has_to_be_packed (p_s_inode) || 
1483         !page || (REISERFS_I(p_s_inode)->i_flags & i_nopack_mask)) {
1484         // leave tail in an unformatted node    
1485         *p_c_mode = M_SKIP_BALANCING;
1486         cut_bytes = n_block_size - (n_new_file_size & (n_block_size - 1));
1487         pathrelse(p_s_path);
1488         return cut_bytes;
1489     }
1490     /* Permorm the conversion to a direct_item. */
1491     /*return indirect_to_direct (p_s_inode, p_s_path, p_s_item_key, n_new_file_size, p_c_mode);*/
1492     return indirect2direct (th, p_s_inode, page, p_s_path, p_s_item_key, n_new_file_size, p_c_mode);
1493 }
1494
1495
1496 /* we did indirect_to_direct conversion. And we have inserted direct
1497    item successesfully, but there were no disk space to cut unfm
1498    pointer being converted. Therefore we have to delete inserted
1499    direct item(s) */
1500 static void indirect_to_direct_roll_back (struct reiserfs_transaction_handle *th, struct inode * inode, struct path * path)
1501 {
1502     struct cpu_key tail_key;
1503     int tail_len;
1504     int removed;
1505
1506     make_cpu_key (&tail_key, inode, inode->i_size + 1, TYPE_DIRECT, 4);// !!!!
1507     tail_key.key_length = 4;
1508
1509     tail_len = (cpu_key_k_offset (&tail_key) & (inode->i_sb->s_blocksize - 1)) - 1;
1510     while (tail_len) {
1511         /* look for the last byte of the tail */
1512         if (search_for_position_by_key (inode->i_sb, &tail_key, path) == POSITION_NOT_FOUND)
1513             reiserfs_panic (inode->i_sb, "vs-5615: indirect_to_direct_roll_back: found invalid item");
1514         RFALSE( path->pos_in_item != ih_item_len(PATH_PITEM_HEAD (path)) - 1,
1515                 "vs-5616: appended bytes found");
1516         PATH_LAST_POSITION (path) --;
1517         
1518         removed = reiserfs_delete_item (th, path, &tail_key, inode, 0/*unbh not needed*/);
1519         RFALSE( removed <= 0 || removed > tail_len,
1520                 "vs-5617: there was tail %d bytes, removed item length %d bytes",
1521                 tail_len, removed);
1522         tail_len -= removed;
1523         set_cpu_key_k_offset (&tail_key, cpu_key_k_offset (&tail_key) - removed);
1524     }
1525     reiserfs_warning (inode->i_sb, "indirect_to_direct_roll_back: indirect_to_direct conversion has been rolled back due to lack of disk space");
1526     //mark_file_without_tail (inode);
1527     mark_inode_dirty (inode);
1528 }
1529
1530
1531 /* (Truncate or cut entry) or delete object item. Returns < 0 on failure */
1532 int reiserfs_cut_from_item (struct reiserfs_transaction_handle *th, 
1533                             struct path * p_s_path,
1534                             struct cpu_key * p_s_item_key,
1535                             struct inode * p_s_inode,
1536                             struct page *page, 
1537                             loff_t n_new_file_size)
1538 {
1539     struct super_block * p_s_sb = p_s_inode->i_sb;
1540     /* Every function which is going to call do_balance must first
1541        create a tree_balance structure.  Then it must fill up this
1542        structure by using the init_tb_struct and fix_nodes functions.
1543        After that we can make tree balancing. */
1544     struct tree_balance s_cut_balance;
1545     struct item_head *p_le_ih;
1546     int n_cut_size = 0,        /* Amount to be cut. */
1547         n_ret_value = CARRY_ON,
1548         n_removed = 0,     /* Number of the removed unformatted nodes. */
1549         n_is_inode_locked = 0;
1550     char                c_mode;            /* Mode of the balance. */
1551     int retval2 = -1;
1552     int quota_cut_bytes;
1553     
1554     
1555     init_tb_struct(th, &s_cut_balance, p_s_inode->i_sb, p_s_path, n_cut_size);
1556
1557
1558     /* Repeat this loop until we either cut the item without needing
1559        to balance, or we fix_nodes without schedule occurring */
1560     while ( 1 ) {
1561         /* Determine the balance mode, position of the first byte to
1562            be cut, and size to be cut.  In case of the indirect item
1563            free unformatted nodes which are pointed to by the cut
1564            pointers. */
1565       
1566         c_mode = prepare_for_delete_or_cut(th, p_s_inode, p_s_path, p_s_item_key, &n_removed, 
1567                                            &n_cut_size, n_new_file_size);
1568         if ( c_mode == M_CONVERT )  {
1569             /* convert last unformatted node to direct item or leave
1570                tail in the unformatted node */
1571             RFALSE( n_ret_value != CARRY_ON, "PAP-5570: can not convert twice");
1572
1573             n_ret_value = maybe_indirect_to_direct (th, p_s_inode, page, p_s_path, p_s_item_key,
1574                                                     n_new_file_size, &c_mode);
1575             if ( c_mode == M_SKIP_BALANCING )
1576                 /* tail has been left in the unformatted node */
1577                 return n_ret_value;
1578
1579             n_is_inode_locked = 1;
1580           
1581             /* removing of last unformatted node will change value we
1582                have to return to truncate. Save it */
1583             retval2 = n_ret_value;
1584             /*retval2 = p_s_sb->s_blocksize - (n_new_file_size & (p_s_sb->s_blocksize - 1));*/
1585           
1586             /* So, we have performed the first part of the conversion:
1587                inserting the new direct item.  Now we are removing the
1588                last unformatted node pointer. Set key to search for
1589                it. */
1590             set_cpu_key_k_type (p_s_item_key, TYPE_INDIRECT);
1591             p_s_item_key->key_length = 4;
1592             n_new_file_size -= (n_new_file_size & (p_s_sb->s_blocksize - 1));
1593             set_cpu_key_k_offset (p_s_item_key, n_new_file_size + 1);
1594             if ( search_for_position_by_key(p_s_sb, p_s_item_key, p_s_path) == POSITION_NOT_FOUND ){
1595                 print_block (PATH_PLAST_BUFFER (p_s_path), 3, PATH_LAST_POSITION (p_s_path) - 1, PATH_LAST_POSITION (p_s_path) + 1);
1596                 reiserfs_panic(p_s_sb, "PAP-5580: reiserfs_cut_from_item: item to convert does not exist (%K)", p_s_item_key);
1597             }
1598             continue;
1599         }
1600         if (n_cut_size == 0) {
1601             pathrelse (p_s_path);
1602             return 0;
1603         }
1604
1605         s_cut_balance.insert_size[0] = n_cut_size;
1606         
1607         n_ret_value = fix_nodes(c_mode, &s_cut_balance, NULL, 0);
1608         if ( n_ret_value != REPEAT_SEARCH )
1609             break;
1610         
1611         PROC_INFO_INC( p_s_sb, cut_from_item_restarted );
1612
1613         n_ret_value = search_for_position_by_key(p_s_sb, p_s_item_key, p_s_path);
1614         if (n_ret_value == POSITION_FOUND)
1615             continue;
1616
1617         reiserfs_warning (p_s_sb, "PAP-5610: reiserfs_cut_from_item: item %K not found", p_s_item_key);
1618         unfix_nodes (&s_cut_balance);
1619         return (n_ret_value == IO_ERROR) ? -EIO : -ENOENT;
1620     } /* while */
1621   
1622     // check fix_nodes results (IO_ERROR or NO_DISK_SPACE)
1623     if ( n_ret_value != CARRY_ON ) {
1624         if ( n_is_inode_locked ) {
1625             // FIXME: this seems to be not needed: we are always able
1626             // to cut item
1627             indirect_to_direct_roll_back (th, p_s_inode, p_s_path);
1628         }
1629         if (n_ret_value == NO_DISK_SPACE)
1630             reiserfs_warning (p_s_sb, "NO_DISK_SPACE");
1631         unfix_nodes (&s_cut_balance);
1632         return -EIO;
1633     }
1634
1635     /* go ahead and perform balancing */
1636     
1637     RFALSE( c_mode == M_PASTE || c_mode == M_INSERT, "invalid mode");
1638
1639     /* Calculate number of bytes that need to be cut from the item. */
1640     quota_cut_bytes = ( c_mode == M_DELETE ) ? ih_item_len(get_ih(p_s_path)) : -s_cut_balance.insert_size[0];
1641     if (retval2 == -1)
1642         n_ret_value = calc_deleted_bytes_number(&s_cut_balance, c_mode);
1643     else
1644         n_ret_value = retval2;
1645
1646
1647     /* For direct items, we only change the quota when deleting the last
1648     ** item.
1649     */
1650     p_le_ih = PATH_PITEM_HEAD (s_cut_balance.tb_path);
1651     if (!S_ISLNK (p_s_inode->i_mode) && is_direct_le_ih(p_le_ih)) {
1652         if (c_mode == M_DELETE &&
1653            (le_ih_k_offset (p_le_ih) & (p_s_sb->s_blocksize - 1)) == 1 ) {
1654             // FIXME: this is to keep 3.5 happy
1655             REISERFS_I(p_s_inode)->i_first_direct_byte = U32_MAX;
1656             quota_cut_bytes = p_s_sb->s_blocksize + UNFM_P_SIZE ;
1657         } else {
1658             quota_cut_bytes = 0 ;
1659         }
1660     }
1661 #ifdef CONFIG_REISERFS_CHECK
1662     if (n_is_inode_locked) {
1663         struct item_head * le_ih = PATH_PITEM_HEAD (s_cut_balance.tb_path);
1664         /* we are going to complete indirect2direct conversion. Make
1665            sure, that we exactly remove last unformatted node pointer
1666            of the item */
1667         if (!is_indirect_le_ih (le_ih))
1668             reiserfs_panic (p_s_sb, "vs-5652: reiserfs_cut_from_item: "
1669                             "item must be indirect %h", le_ih);
1670
1671         if (c_mode == M_DELETE && ih_item_len(le_ih) != UNFM_P_SIZE)
1672             reiserfs_panic (p_s_sb, "vs-5653: reiserfs_cut_from_item: "
1673                             "completing indirect2direct conversion indirect item %h "
1674                             "being deleted must be of 4 byte long", le_ih);
1675
1676         if (c_mode == M_CUT && s_cut_balance.insert_size[0] != -UNFM_P_SIZE) {
1677             reiserfs_panic (p_s_sb, "vs-5654: reiserfs_cut_from_item: "
1678                             "can not complete indirect2direct conversion of %h (CUT, insert_size==%d)",
1679                             le_ih, s_cut_balance.insert_size[0]);
1680         }
1681         /* it would be useful to make sure, that right neighboring
1682            item is direct item of this file */
1683     }
1684 #endif
1685     
1686     do_balance(&s_cut_balance, NULL, NULL, c_mode);
1687     if ( n_is_inode_locked ) {
1688         /* we've done an indirect->direct conversion.  when the data block
1689         ** was freed, it was removed from the list of blocks that must
1690         ** be flushed before the transaction commits, so we don't need to
1691         ** deal with it here.
1692         */
1693         REISERFS_I(p_s_inode)->i_flags &= ~i_pack_on_close_mask ;
1694     }
1695 #ifdef REISERQUOTA_DEBUG
1696     reiserfs_debug (p_s_inode->i_sb, "reiserquota cut_from_item(): freeing %u id=%u type=%c", quota_cut_bytes, p_s_inode->i_uid, '?');
1697 #endif
1698     DQUOT_FREE_SPACE_NODIRTY(p_s_inode, quota_cut_bytes);
1699     return n_ret_value;
1700 }
1701
1702 static void truncate_directory (struct reiserfs_transaction_handle *th, struct inode * inode)
1703 {
1704     if (inode->i_nlink)
1705         reiserfs_warning (inode->i_sb,
1706                           "vs-5655: truncate_directory: link count != 0");
1707
1708     set_le_key_k_offset (KEY_FORMAT_3_5, INODE_PKEY (inode), DOT_OFFSET);
1709     set_le_key_k_type (KEY_FORMAT_3_5, INODE_PKEY (inode), TYPE_DIRENTRY);
1710     reiserfs_delete_solid_item (th, inode, INODE_PKEY (inode));
1711     reiserfs_update_sd(th, inode) ;
1712     set_le_key_k_offset (KEY_FORMAT_3_5, INODE_PKEY (inode), SD_OFFSET);
1713     set_le_key_k_type (KEY_FORMAT_3_5, INODE_PKEY (inode), TYPE_STAT_DATA);    
1714 }
1715
1716
1717
1718
1719 /* Truncate file to the new size. Note, this must be called with a transaction
1720    already started */
1721 void reiserfs_do_truncate (struct reiserfs_transaction_handle *th, 
1722                            struct  inode * p_s_inode, /* ->i_size contains new
1723                                                          size */
1724                            struct page *page, /* up to date for last block */
1725                            int update_timestamps  /* when it is called by
1726                                                      file_release to convert
1727                                                      the tail - no timestamps
1728                                                      should be updated */
1729     ) {
1730     INITIALIZE_PATH (s_search_path);       /* Path to the current object item. */
1731     struct item_head    * p_le_ih;         /* Pointer to an item header. */
1732     struct cpu_key      s_item_key;     /* Key to search for a previous file item. */
1733     loff_t         n_file_size,    /* Old file size. */
1734         n_new_file_size;/* New file size. */
1735     int                   n_deleted;      /* Number of deleted or truncated bytes. */
1736     int retval;
1737
1738     if ( ! (S_ISREG(p_s_inode->i_mode) || S_ISDIR(p_s_inode->i_mode) || S_ISLNK(p_s_inode->i_mode)) )
1739         return;
1740
1741     if (S_ISDIR(p_s_inode->i_mode)) {
1742         // deletion of directory - no need to update timestamps
1743         truncate_directory (th, p_s_inode);
1744         return;
1745     }
1746
1747     /* Get new file size. */
1748     n_new_file_size = p_s_inode->i_size;
1749
1750     // FIXME: note, that key type is unimportant here
1751     make_cpu_key (&s_item_key, p_s_inode, max_reiserfs_offset (p_s_inode), TYPE_DIRECT, 3);
1752
1753     retval = search_for_position_by_key(p_s_inode->i_sb, &s_item_key, &s_search_path);
1754     if (retval == IO_ERROR) {
1755         reiserfs_warning (p_s_inode->i_sb, "vs-5657: reiserfs_do_truncate: "
1756                           "i/o failure occurred trying to truncate %K", &s_item_key);
1757         return;
1758     }
1759     if (retval == POSITION_FOUND || retval == FILE_NOT_FOUND) {
1760         pathrelse (&s_search_path);
1761         reiserfs_warning (p_s_inode->i_sb, "PAP-5660: reiserfs_do_truncate: "
1762                           "wrong result %d of search for %K", retval, &s_item_key);
1763         return;
1764     }
1765
1766     s_search_path.pos_in_item --;
1767
1768     /* Get real file size (total length of all file items) */
1769     p_le_ih = PATH_PITEM_HEAD(&s_search_path);
1770     if ( is_statdata_le_ih (p_le_ih) )
1771         n_file_size = 0;
1772     else {
1773         loff_t offset = le_ih_k_offset (p_le_ih);
1774         int bytes = op_bytes_number (p_le_ih,p_s_inode->i_sb->s_blocksize);
1775
1776         /* this may mismatch with real file size: if last direct item
1777            had no padding zeros and last unformatted node had no free
1778            space, this file would have this file size */
1779         n_file_size = offset + bytes - 1;
1780     }
1781
1782     if ( n_file_size == 0 || n_file_size < n_new_file_size ) {
1783         goto update_and_out ;
1784     }
1785
1786     /* Update key to search for the last file item. */
1787     set_cpu_key_k_offset (&s_item_key, n_file_size);
1788
1789     do  {
1790         /* Cut or delete file item. */
1791         n_deleted = reiserfs_cut_from_item(th, &s_search_path, &s_item_key, p_s_inode,  page, n_new_file_size);
1792         if (n_deleted < 0) {
1793             reiserfs_warning (p_s_inode->i_sb, "vs-5665: reiserfs_do_truncate: reiserfs_cut_from_item failed");
1794             reiserfs_check_path(&s_search_path) ;
1795             return;
1796         }
1797
1798         RFALSE( n_deleted > n_file_size,
1799                 "PAP-5670: reiserfs_cut_from_item: too many bytes deleted: deleted %d, file_size %lu, item_key %K",
1800                 n_deleted, n_file_size, &s_item_key);
1801
1802         /* Change key to search the last file item. */
1803         n_file_size -= n_deleted;
1804
1805         set_cpu_key_k_offset (&s_item_key, n_file_size);
1806
1807         /* While there are bytes to truncate and previous file item is presented in the tree. */
1808
1809         /*
1810         ** This loop could take a really long time, and could log 
1811         ** many more blocks than a transaction can hold.  So, we do a polite
1812         ** journal end here, and if the transaction needs ending, we make
1813         ** sure the file is consistent before ending the current trans
1814         ** and starting a new one
1815         */
1816         if (journal_transaction_should_end(th, th->t_blocks_allocated)) {
1817           int orig_len_alloc = th->t_blocks_allocated ;
1818           decrement_counters_in_path(&s_search_path) ;
1819
1820           if (update_timestamps) {
1821               p_s_inode->i_mtime = p_s_inode->i_ctime = CURRENT_TIME;
1822           } 
1823           reiserfs_update_sd(th, p_s_inode) ;
1824
1825           journal_end(th, p_s_inode->i_sb, orig_len_alloc) ;
1826           journal_begin(th, p_s_inode->i_sb, JOURNAL_PER_BALANCE_CNT * 6) ;
1827           reiserfs_update_inode_transaction(p_s_inode) ;
1828         }
1829     } while ( n_file_size > ROUND_UP (n_new_file_size) &&
1830               search_for_position_by_key(p_s_inode->i_sb, &s_item_key, &s_search_path) == POSITION_FOUND )  ;
1831
1832     RFALSE( n_file_size > ROUND_UP (n_new_file_size),
1833             "PAP-5680: truncate did not finish: new_file_size %Ld, current %Ld, oid %d",
1834             n_new_file_size, n_file_size, s_item_key.on_disk_key.k_objectid);
1835
1836 update_and_out:
1837     if (update_timestamps) {
1838         // this is truncate, not file closing
1839         p_s_inode->i_mtime = p_s_inode->i_ctime = CURRENT_TIME;
1840     }
1841     reiserfs_update_sd (th, p_s_inode);
1842
1843     pathrelse(&s_search_path) ;
1844 }
1845
1846
1847 #ifdef CONFIG_REISERFS_CHECK
1848 // this makes sure, that we __append__, not overwrite or add holes
1849 static void check_research_for_paste (struct path * path, 
1850                                       const struct cpu_key * p_s_key)
1851 {
1852     struct item_head * found_ih = get_ih (path);
1853     
1854     if (is_direct_le_ih (found_ih)) {
1855         if (le_ih_k_offset (found_ih) + op_bytes_number (found_ih, get_last_bh (path)->b_size) !=
1856             cpu_key_k_offset (p_s_key) ||
1857             op_bytes_number (found_ih, get_last_bh (path)->b_size) != pos_in_item (path))
1858             reiserfs_panic (0, "PAP-5720: check_research_for_paste: "
1859                             "found direct item %h or position (%d) does not match to key %K",
1860                             found_ih, pos_in_item (path), p_s_key);
1861     }
1862     if (is_indirect_le_ih (found_ih)) {
1863         if (le_ih_k_offset (found_ih) + op_bytes_number (found_ih, get_last_bh (path)->b_size) != cpu_key_k_offset (p_s_key) || 
1864             I_UNFM_NUM (found_ih) != pos_in_item (path) ||
1865             get_ih_free_space (found_ih) != 0)
1866             reiserfs_panic (0, "PAP-5730: check_research_for_paste: "
1867                             "found indirect item (%h) or position (%d) does not match to key (%K)",
1868                             found_ih, pos_in_item (path), p_s_key);
1869     }
1870 }
1871 #endif /* config reiserfs check */
1872
1873
1874 /* Paste bytes to the existing item. Returns bytes number pasted into the item. */
1875 int reiserfs_paste_into_item (struct reiserfs_transaction_handle *th, 
1876                               struct path         * p_s_search_path,    /* Path to the pasted item.          */
1877                               const struct cpu_key      * p_s_key,              /* Key to search for the needed item.*/
1878                               struct inode        * inode,              /* Inode item belongs to */
1879                               const char          * p_c_body,           /* Pointer to the bytes to paste.    */
1880                               int                   n_pasted_size)      /* Size of pasted bytes.             */
1881 {
1882     struct tree_balance s_paste_balance;
1883     int                 retval;
1884     int                 fs_gen;
1885
1886     fs_gen = get_generation(inode->i_sb) ;
1887
1888 #ifdef REISERQUOTA_DEBUG
1889     reiserfs_debug (inode->i_sb, "reiserquota paste_into_item(): allocating %u id=%u type=%c", n_pasted_size, inode->i_uid, key2type(&(p_s_key->on_disk_key)));
1890 #endif
1891
1892     if (DQUOT_ALLOC_SPACE_NODIRTY(inode, n_pasted_size)) {
1893         pathrelse(p_s_search_path);
1894         return -EDQUOT;
1895     }
1896     init_tb_struct(th, &s_paste_balance, th->t_super, p_s_search_path, n_pasted_size);
1897 #ifdef DISPLACE_NEW_PACKING_LOCALITIES
1898     s_paste_balance.key = p_s_key->on_disk_key;
1899 #endif
1900
1901     /* DQUOT_* can schedule, must check before the fix_nodes */
1902     if (fs_changed(fs_gen, inode->i_sb)) {
1903         goto search_again;
1904     }
1905
1906     while ((retval = fix_nodes(M_PASTE, &s_paste_balance, NULL, p_c_body)) ==
1907 REPEAT_SEARCH ) {
1908 search_again:
1909         /* file system changed while we were in the fix_nodes */
1910         PROC_INFO_INC( th -> t_super, paste_into_item_restarted );
1911         retval = search_for_position_by_key (th->t_super, p_s_key, p_s_search_path);
1912         if (retval == IO_ERROR) {
1913             retval = -EIO ;
1914             goto error_out ;
1915         }
1916         if (retval == POSITION_FOUND) {
1917             reiserfs_warning (inode->i_sb, "PAP-5710: reiserfs_paste_into_item: entry or pasted byte (%K) exists", p_s_key);
1918             retval = -EEXIST ;
1919             goto error_out ;
1920         }
1921         
1922 #ifdef CONFIG_REISERFS_CHECK
1923         check_research_for_paste (p_s_search_path, p_s_key);
1924 #endif
1925     }
1926
1927     /* Perform balancing after all resources are collected by fix_nodes, and
1928        accessing them will not risk triggering schedule. */
1929     if ( retval == CARRY_ON ) {
1930         do_balance(&s_paste_balance, NULL/*ih*/, p_c_body, M_PASTE);
1931         return 0;
1932     }
1933     retval = (retval == NO_DISK_SPACE) ? -ENOSPC : -EIO;
1934 error_out:
1935     /* this also releases the path */
1936     unfix_nodes(&s_paste_balance);
1937 #ifdef REISERQUOTA_DEBUG
1938     reiserfs_debug (inode->i_sb, "reiserquota paste_into_item(): freeing %u id=%u type=%c", n_pasted_size, inode->i_uid, key2type(&(p_s_key->on_disk_key)));
1939 #endif
1940     DQUOT_FREE_SPACE_NODIRTY(inode, n_pasted_size);
1941     return retval ;
1942 }
1943
1944
1945 /* Insert new item into the buffer at the path. */
1946 int reiserfs_insert_item(struct reiserfs_transaction_handle *th, 
1947                          struct path         *  p_s_path,         /* Path to the inserteded item.         */
1948                          const struct cpu_key      * key,
1949                          struct item_head    *  p_s_ih,           /* Pointer to the item header to insert.*/
1950                          struct inode        * inode,
1951                          const char          *  p_c_body)         /* Pointer to the bytes to insert.      */
1952 {
1953     struct tree_balance s_ins_balance;
1954     int                 retval;
1955     int fs_gen = 0 ;
1956     int quota_bytes = 0 ;
1957
1958     if (inode) {      /* Do we count quotas for item? */
1959         fs_gen = get_generation(inode->i_sb);
1960         quota_bytes = ih_item_len(p_s_ih);
1961
1962         /* hack so the quota code doesn't have to guess if the file has
1963          ** a tail, links are always tails, so there's no guessing needed
1964          */
1965         if (!S_ISLNK (inode->i_mode) && is_direct_le_ih(p_s_ih)) {
1966             quota_bytes = inode->i_sb->s_blocksize + UNFM_P_SIZE ;
1967         }
1968 #ifdef REISERQUOTA_DEBUG
1969         reiserfs_debug (inode->i_sb, "reiserquota insert_item(): allocating %u id=%u type=%c", quota_bytes, inode->i_uid, head2type(p_s_ih));
1970 #endif
1971         /* We can't dirty inode here. It would be immediately written but
1972          * appropriate stat item isn't inserted yet... */
1973         if (DQUOT_ALLOC_SPACE_NODIRTY(inode, quota_bytes)) {
1974             pathrelse(p_s_path);
1975             return -EDQUOT;
1976         }
1977     }
1978     init_tb_struct(th, &s_ins_balance, th->t_super, p_s_path, IH_SIZE + ih_item_len(p_s_ih));
1979 #ifdef DISPLACE_NEW_PACKING_LOCALITIES
1980     s_ins_balance.key = key->on_disk_key;
1981 #endif
1982     /* DQUOT_* can schedule, must check to be sure calling fix_nodes is safe */
1983     if (inode && fs_changed(fs_gen, inode->i_sb)) {
1984         goto search_again;
1985     }
1986
1987     while ( (retval = fix_nodes(M_INSERT, &s_ins_balance, p_s_ih, p_c_body)) == REPEAT_SEARCH) {
1988 search_again:
1989         /* file system changed while we were in the fix_nodes */
1990         PROC_INFO_INC( th -> t_super, insert_item_restarted );
1991         retval = search_item (th->t_super, key, p_s_path);
1992         if (retval == IO_ERROR) {
1993             retval = -EIO;
1994             goto error_out ;
1995         }
1996         if (retval == ITEM_FOUND) {
1997             reiserfs_warning (th->t_super, "PAP-5760: reiserfs_insert_item: "
1998                               "key %K already exists in the tree", key);
1999             retval = -EEXIST ;
2000             goto error_out; 
2001         }
2002     }
2003
2004     /* make balancing after all resources will be collected at a time */ 
2005     if ( retval == CARRY_ON ) {
2006         do_balance (&s_ins_balance, p_s_ih, p_c_body, M_INSERT);
2007         return 0;
2008     }
2009
2010     retval = (retval == NO_DISK_SPACE) ? -ENOSPC : -EIO;
2011 error_out:
2012     /* also releases the path */
2013     unfix_nodes(&s_ins_balance);
2014 #ifdef REISERQUOTA_DEBUG
2015     reiserfs_debug (th->t_super, "reiserquota insert_item(): freeing %u id=%u type=%c", quota_bytes, inode->i_uid, head2type(p_s_ih));
2016 #endif
2017     if (inode)
2018         DQUOT_FREE_SPACE_NODIRTY(inode, quota_bytes) ;
2019     return retval; 
2020 }
2021
2022
2023
2024