xref: /dragonfly/sys/vfs/ntfs/ntfs_subr.c (revision 33311965)
1 /*	$NetBSD: ntfs_subr.c,v 1.23 1999/10/31 19:45:26 jdolecek Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 1999 Semen Ustimenko (semenu@FreeBSD.org)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/ntfs/ntfs_subr.c,v 1.7.2.4 2001/10/12 22:08:49 semenu Exp $
29  */
30 
31 #include <sys/param.h>
32 #include <sys/types.h>
33 #include <sys/systm.h>
34 #include <sys/proc.h>
35 #include <sys/namei.h>
36 #include <sys/kernel.h>
37 #include <sys/vnode.h>
38 #include <sys/mount.h>
39 #include <sys/buf.h>
40 #include <sys/file.h>
41 #include <sys/malloc.h>
42 #include <sys/lock.h>
43 #include <sys/spinlock.h>
44 #include <sys/iconv.h>
45 
46 #include <machine/inttypes.h>
47 
48 #include <sys/buf2.h>
49 #include <sys/spinlock2.h>
50 
51 #include "ntfs.h"
52 #include "ntfsmount.h"
53 #include "ntfs_inode.h"
54 #include "ntfs_vfsops.h"
55 #include "ntfs_subr.h"
56 #include "ntfs_compr.h"
57 #include "ntfs_ihash.h"
58 
59 MALLOC_DEFINE(M_NTFSNTVATTR, "NTFS vattr", "NTFS file attribute information");
60 MALLOC_DEFINE(M_NTFSRDATA, "NTFS res data", "NTFS resident data");
61 MALLOC_DEFINE(M_NTFSRUN, "NTFS vrun", "NTFS vrun storage");
62 MALLOC_DEFINE(M_NTFSDECOMP, "NTFS decomp", "NTFS decompression temporary");
63 
64 static int ntfs_ntlookupattr (struct ntfsmount *, const char *, int, int *, char **);
65 static int ntfs_findvattr (struct ntfsmount *, struct ntnode *, struct ntvattr **, struct ntvattr **, u_int32_t, const char *, size_t, cn_t);
66 static int ntfs_uastricmp (struct ntfsmount *, const wchar *, size_t, const char *, size_t);
67 static int ntfs_uastrcmp (struct ntfsmount *, const wchar *, size_t, const char *, size_t);
68 
69 /* table for mapping Unicode chars into uppercase; it's filled upon first
70  * ntfs mount, freed upon last ntfs umount */
71 static wchar *ntfs_toupper_tab;
72 #define NTFS_TOUPPER(ch)	(ntfs_toupper_tab[(ch)])
73 static struct lock ntfs_toupper_lock;
74 static signed int ntfs_toupper_usecount;
75 extern struct iconv_functions *ntfs_iconv;
76 
77 /* support macro for ntfs_ntvattrget() */
78 #define NTFS_AALPCMP(aalp,type,name,namelen) (				\
79   (aalp->al_type == type) && (aalp->al_namelen == namelen) &&		\
80   !NTFS_UASTRCMP(aalp->al_name,aalp->al_namelen,name,namelen) )
81 
82 /*
83  *
84  */
85 int
86 ntfs_ntvattrrele(struct ntvattr *vap)
87 {
88 	dprintf(("ntfs_ntvattrrele: ino: %"PRId64", type: 0x%x\n",
89 		 vap->va_ip->i_number, vap->va_type));
90 
91 	ntfs_ntrele(vap->va_ip);
92 
93 	return (0);
94 }
95 
96 /*
97  * find the attribute in the ntnode
98  */
99 static int
100 ntfs_findvattr(struct ntfsmount *ntmp, struct ntnode *ip,
101 	       struct ntvattr **lvapp, struct ntvattr **vapp, u_int32_t type,
102 	       const char *name, size_t namelen, cn_t vcn)
103 {
104 	int error;
105 	struct ntvattr *vap;
106 
107 	if((ip->i_flag & IN_LOADED) == 0) {
108 		dprintf(("ntfs_findvattr: node not loaded, ino: %"PRId64"\n",
109 		       ip->i_number));
110 		error = ntfs_loadntnode(ntmp,ip);
111 		if (error) {
112 			kprintf("ntfs_findvattr: FAILED TO LOAD INO: %"PRId64"\n",
113 			       ip->i_number);
114 			return (error);
115 		}
116 	}
117 
118 	*lvapp = NULL;
119 	*vapp = NULL;
120 	for (vap = ip->i_valist.lh_first; vap; vap = vap->va_list.le_next) {
121 		ddprintf(("ntfs_findvattr: type: 0x%x, vcn: %d - %d\n", \
122 			  vap->va_type, (u_int32_t) vap->va_vcnstart, \
123 			  (u_int32_t) vap->va_vcnend));
124 		if ((vap->va_type == type) &&
125 		    (vap->va_vcnstart <= vcn) && (vap->va_vcnend >= vcn) &&
126 		    (vap->va_namelen == namelen) &&
127 		    (strncmp(name, vap->va_name, namelen) == 0)) {
128 			*vapp = vap;
129 			ntfs_ntref(vap->va_ip);
130 			return (0);
131 		}
132 		if (vap->va_type == NTFS_A_ATTRLIST)
133 			*lvapp = vap;
134 	}
135 
136 	return (-1);
137 }
138 
139 /*
140  * Search attribute specifed in ntnode (load ntnode if nessecary).
141  * If not found but ATTR_A_ATTRLIST present, read it in and search throught.
142  * VOP_VGET node needed, and lookup througth it's ntnode (load if nessesary).
143  *
144  * ntnode should be locked
145  */
146 int
147 ntfs_ntvattrget(struct ntfsmount *ntmp, struct ntnode *ip, u_int32_t type,
148 		const char *name, cn_t vcn, struct ntvattr **vapp)
149 {
150 	struct ntvattr *lvap = NULL;
151 	struct attr_attrlist *aalp;
152 	struct attr_attrlist *nextaalp;
153 	struct vnode   *newvp;
154 	struct ntnode  *newip;
155 	caddr_t         alpool;
156 	size_t		namelen, len;
157 	int             error;
158 
159 	*vapp = NULL;
160 
161 	if (name) {
162 		dprintf(("ntfs_ntvattrget: " \
163 			 "ino: %"PRId64", type: 0x%x, name: %s, vcn: %d\n", \
164 			 ip->i_number, type, name, (u_int32_t) vcn));
165 		namelen = strlen(name);
166 	} else {
167 		dprintf(("ntfs_ntvattrget: " \
168 			 "ino: %"PRId64", type: 0x%x, vcn: %d\n", \
169 			 ip->i_number, type, (u_int32_t) vcn));
170 		name = "";
171 		namelen = 0;
172 	}
173 
174 	error = ntfs_findvattr(ntmp, ip, &lvap, vapp, type, name, namelen, vcn);
175 	if (error >= 0)
176 		return (error);
177 
178 	if (!lvap) {
179 		dprintf(("ntfs_ntvattrget: UNEXISTED ATTRIBUTE: " \
180 		       "ino: %"PRId64", type: 0x%x, name: %s, vcn: %d\n", \
181 		       ip->i_number, type, name, (u_int32_t) vcn));
182 		return (ENOENT);
183 	}
184 	/* Scan $ATTRIBUTE_LIST for requested attribute */
185 	len = lvap->va_datalen;
186 	alpool = kmalloc(len, M_TEMP, M_WAITOK);
187 	error = ntfs_readntvattr_plain(ntmp, ip, lvap, 0, len, alpool, &len,
188 			NULL);
189 	if (error)
190 		goto out;
191 
192 	aalp = (struct attr_attrlist *) alpool;
193 	nextaalp = NULL;
194 
195 	for(; len > 0; aalp = nextaalp) {
196 		dprintf(("ntfs_ntvattrget: " \
197 			 "attrlist: ino: %d, attr: 0x%x, vcn: %d\n", \
198 			 aalp->al_inumber, aalp->al_type, \
199 			 (u_int32_t) aalp->al_vcnstart));
200 
201 		if (len > aalp->reclen) {
202 			nextaalp = NTFS_NEXTREC(aalp, struct attr_attrlist *);
203 		} else {
204 			nextaalp = NULL;
205 		}
206 		len -= aalp->reclen;
207 
208 		if (!NTFS_AALPCMP(aalp, type, name, namelen) ||
209 		    (nextaalp && (nextaalp->al_vcnstart <= vcn) &&
210 		     NTFS_AALPCMP(nextaalp, type, name, namelen)))
211 			continue;
212 
213 		dprintf(("ntfs_ntvattrget: attribute in ino: %d\n",
214 				 aalp->al_inumber));
215 
216 		/* this is not a main record, so we can't use just plain
217 		   vget() */
218 		error = ntfs_vgetex(ntmp->ntm_mountp, aalp->al_inumber,
219 				NTFS_A_DATA, NULL, LK_EXCLUSIVE,
220 				VG_EXT, curthread, &newvp);
221 		if (error) {
222 			kprintf("ntfs_ntvattrget: CAN'T VGET INO: %d\n",
223 			       aalp->al_inumber);
224 			goto out;
225 		}
226 		newip = VTONT(newvp);
227 		/* XXX have to lock ntnode */
228 		error = ntfs_findvattr(ntmp, newip, &lvap, vapp,
229 				type, name, namelen, vcn);
230 		vput(newvp);
231 		if (error == 0)
232 			goto out;
233 		kprintf("ntfs_ntvattrget: ATTRLIST ERROR.\n");
234 		break;
235 	}
236 	error = ENOENT;
237 
238 	dprintf(("ntfs_ntvattrget: UNEXISTED ATTRIBUTE: " \
239 	       "ino: %"PRId64", type: 0x%x, name: %.*s, vcn: %d\n", \
240 	       ip->i_number, type, (int) namelen, name, (u_int32_t) vcn));
241 out:
242 	kfree(alpool, M_TEMP);
243 	return (error);
244 }
245 
246 /*
247  * Read ntnode from disk, make ntvattr list.
248  *
249  * ntnode should be locked
250  */
251 int
252 ntfs_loadntnode(struct ntfsmount *ntmp, struct ntnode *ip)
253 {
254 	struct filerec  *mfrp;
255 	daddr_t         bn;
256 	int		error,off;
257 	struct attr    *ap;
258 	struct ntvattr *nvap;
259 
260 	dprintf(("ntfs_loadntnode: loading ino: %"PRId64"\n",ip->i_number));
261 
262 	mfrp = kmalloc(ntfs_bntob(ntmp->ntm_bpmftrec), M_TEMP, M_WAITOK);
263 
264 	if (ip->i_number < NTFS_SYSNODESNUM) {
265 		struct buf     *bp;
266 
267 		dprintf(("ntfs_loadntnode: read system node\n"));
268 
269 		bn = ntfs_cntobn(ntmp->ntm_mftcn) +
270 			ntmp->ntm_bpmftrec * ip->i_number;
271 
272 		error = bread(ntmp->ntm_devvp,
273 			      ntfs_bntodoff(bn), ntfs_bntob(ntmp->ntm_bpmftrec), &bp);
274 		if (error) {
275 			kprintf("ntfs_loadntnode: BREAD FAILED\n");
276 			brelse(bp);
277 			goto out;
278 		}
279 		memcpy(mfrp, bp->b_data, ntfs_bntob(ntmp->ntm_bpmftrec));
280 		bqrelse(bp);
281 	} else {
282 		struct vnode   *vp;
283 
284 		vp = ntmp->ntm_sysvn[NTFS_MFTINO];
285 		error = ntfs_readattr(ntmp, VTONT(vp), NTFS_A_DATA, NULL,
286 			       ip->i_number * ntfs_bntob(ntmp->ntm_bpmftrec),
287 			       ntfs_bntob(ntmp->ntm_bpmftrec), mfrp, NULL);
288 		if (error) {
289 			kprintf("ntfs_loadntnode: ntfs_readattr failed\n");
290 			goto out;
291 		}
292 	}
293 
294 	/* Check if magic and fixups are correct */
295 	error = ntfs_procfixups(ntmp, NTFS_FILEMAGIC, (caddr_t)mfrp,
296 				ntfs_bntob(ntmp->ntm_bpmftrec));
297 	if (error) {
298 		kprintf("ntfs_loadntnode: BAD MFT RECORD %"PRId64"\n",
299 		       ip->i_number);
300 		goto out;
301 	}
302 
303 	dprintf(("ntfs_loadntnode: load attrs for ino: %"PRId64"\n",ip->i_number));
304 	off = mfrp->fr_attroff;
305 	ap = (struct attr *) ((caddr_t)mfrp + off);
306 
307 	LIST_INIT(&ip->i_valist);
308 
309 	while (ap->a_hdr.a_type != -1) {
310 		error = ntfs_attrtontvattr(ntmp, &nvap, ap);
311 		if (error)
312 			break;
313 		nvap->va_ip = ip;
314 
315 		LIST_INSERT_HEAD(&ip->i_valist, nvap, va_list);
316 
317 		off += ap->a_hdr.reclen;
318 		ap = (struct attr *) ((caddr_t)mfrp + off);
319 	}
320 	if (error) {
321 		kprintf("ntfs_loadntnode: failed to load attr ino: %"PRId64"\n",
322 		       ip->i_number);
323 		goto out;
324 	}
325 
326 	ip->i_mainrec = mfrp->fr_mainrec;
327 	ip->i_nlink = mfrp->fr_nlink;
328 	ip->i_frflag = mfrp->fr_flags;
329 
330 	ip->i_flag |= IN_LOADED;
331 
332 out:
333 	kfree(mfrp, M_TEMP);
334 	return (error);
335 }
336 
337 /*
338  * Routine locks ntnode and increase usecount, just opposite of
339  * ntfs_ntput().
340  */
341 int
342 ntfs_ntget(struct ntnode *ip)
343 {
344 	dprintf(("ntfs_ntget: get ntnode %"PRId64": %p, usecount: %d\n",
345 		ip->i_number, ip, ip->i_usecount));
346 
347 	ip->i_usecount++;	/* ZZZ */
348 	LOCKMGR(&ip->i_lock, LK_EXCLUSIVE);
349 
350 	return 0;
351 }
352 
353 /*
354  * Routine search ntnode in hash, if found: lock, inc usecount and return.
355  * If not in hash allocate structure for ntnode, prefill it, lock,
356  * inc count and return.
357  *
358  * ntnode returned locked
359  */
360 int
361 ntfs_ntlookup(struct ntfsmount *ntmp, ino_t ino, struct ntnode **ipp)
362 {
363 	struct ntnode  *ip;
364 
365 	dprintf(("ntfs_ntlookup: looking for ntnode %ju\n", (uintmax_t)ino));
366 
367 	do {
368 		if ((ip = ntfs_nthashlookup(ntmp->ntm_dev, ino)) != NULL) {
369 			ntfs_ntget(ip);
370 			dprintf(("ntfs_ntlookup: ntnode %ju: %p, usecount: %d\n",
371 				(uintmax_t)ino, ip, ip->i_usecount));
372 			*ipp = ip;
373 			return (0);
374 		}
375 	} while (LOCKMGR(&ntfs_hashlock, LK_EXCLUSIVE | LK_SLEEPFAIL));
376 
377 	ip = kmalloc(sizeof(struct ntnode), M_NTFSNTNODE, M_WAITOK | M_ZERO);
378 	ddprintf(("ntfs_ntlookup: allocating ntnode: %ju: %p\n", ino, ip));
379 
380 	/* Generic initialization */
381 	ip->i_devvp = ntmp->ntm_devvp;
382 	ip->i_dev = ntmp->ntm_dev;
383 	ip->i_number = ino;
384 	ip->i_mp = ntmp;
385 
386 	LIST_INIT(&ip->i_fnlist);
387 	vref(ip->i_devvp);
388 
389 	/* init lock and lock the newborn ntnode */
390 	lockinit(&ip->i_lock, "ntnode", 0, LK_EXCLUSIVE);
391 	spin_init(&ip->i_interlock);
392 	ntfs_ntget(ip);
393 
394 	ntfs_nthashins(ip);
395 
396 	LOCKMGR(&ntfs_hashlock, LK_RELEASE);
397 
398 	*ipp = ip;
399 
400 	dprintf(("ntfs_ntlookup: ntnode %ju: %p, usecount: %d\n",
401 		(uintmax_t)ino, ip, ip->i_usecount));
402 
403 	return (0);
404 }
405 
406 /*
407  * Decrement usecount of ntnode and unlock it, if usecount reach zero,
408  * deallocate ntnode.
409  *
410  * ntnode should be locked on entry, and unlocked on return.
411  */
412 void
413 ntfs_ntput(struct ntnode *ip)
414 {
415 	struct ntvattr *vap;
416 
417 	dprintf(("ntfs_ntput: rele ntnode %"PRId64": %p, usecount: %d\n",
418 		ip->i_number, ip, ip->i_usecount));
419 
420 	spin_lock(&ip->i_interlock);
421 	ip->i_usecount--;
422 
423 #ifdef DIAGNOSTIC
424 	if (ip->i_usecount < 0) {
425 		spin_unlock(&ip->i_interlock);
426 		panic("ntfs_ntput: ino: %"PRId64" usecount: %d ",
427 		      ip->i_number,ip->i_usecount);
428 	}
429 #endif
430 
431 	if (ip->i_usecount > 0) {
432 		spin_unlock(&ip->i_interlock);
433 		LOCKMGR(&ip->i_lock, LK_RELEASE);
434 		return;
435 	}
436 
437 	dprintf(("ntfs_ntput: deallocating ntnode: %"PRId64"\n", ip->i_number));
438 
439 	if (ip->i_fnlist.lh_first) {
440 		spin_unlock(&ip->i_interlock);
441 		panic("ntfs_ntput: ntnode has fnodes");
442 	}
443 
444 	/*
445 	 * XXX this is a bit iffy because we are making high level calls
446 	 * while holding a spinlock.
447 	 */
448 	ntfs_nthashrem(ip);
449 
450 	while ((vap = LIST_FIRST(&ip->i_valist)) != NULL) {
451 		LIST_REMOVE(vap,va_list);
452 		ntfs_freentvattr(vap);
453 	}
454 	spin_unlock(&ip->i_interlock);
455 	vrele(ip->i_devvp);
456 	kfree(ip, M_NTFSNTNODE);
457 }
458 
459 /*
460  * increment usecount of ntnode
461  */
462 void
463 ntfs_ntref(struct ntnode *ip)
464 {
465 	ip->i_usecount++;
466 
467 	dprintf(("ntfs_ntref: ino %"PRId64", usecount: %d\n",
468 		ip->i_number, ip->i_usecount));
469 }
470 
471 /*
472  * Decrement usecount of ntnode.
473  */
474 void
475 ntfs_ntrele(struct ntnode *ip)
476 {
477 	dprintf(("ntfs_ntrele: rele ntnode %"PRId64": %p, usecount: %d\n",
478 		ip->i_number, ip, ip->i_usecount));
479 
480 	spin_lock(&ip->i_interlock);
481 	ip->i_usecount--;
482 
483 	if (ip->i_usecount < 0) {
484 		spin_unlock(&ip->i_interlock);
485 		panic("ntfs_ntrele: ino: %"PRId64" usecount: %d ",
486 		      ip->i_number,ip->i_usecount);
487 	}
488 	spin_unlock(&ip->i_interlock);
489 }
490 
491 /*
492  * Deallocate all memory allocated for ntvattr
493  */
494 void
495 ntfs_freentvattr(struct ntvattr *vap)
496 {
497 	if (vap->va_flag & NTFS_AF_INRUN) {
498 		if (vap->va_vruncn)
499 			kfree(vap->va_vruncn, M_NTFSRUN);
500 		if (vap->va_vruncl)
501 			kfree(vap->va_vruncl, M_NTFSRUN);
502 	} else {
503 		if (vap->va_datap)
504 			kfree(vap->va_datap, M_NTFSRDATA);
505 	}
506 	kfree(vap, M_NTFSNTVATTR);
507 }
508 
509 /*
510  * Convert disk image of attribute into ntvattr structure,
511  * runs are expanded also.
512  */
513 int
514 ntfs_attrtontvattr(struct ntfsmount *ntmp, struct ntvattr **rvapp,
515 		   struct attr *rap)
516 {
517 	int             error, i;
518 	struct ntvattr *vap;
519 
520 	error = 0;
521 	*rvapp = NULL;
522 
523 	vap = kmalloc(sizeof(struct ntvattr), M_NTFSNTVATTR,
524 		      M_WAITOK | M_ZERO);
525 	vap->va_ip = NULL;
526 	vap->va_flag = rap->a_hdr.a_flag;
527 	vap->va_type = rap->a_hdr.a_type;
528 	vap->va_compression = rap->a_hdr.a_compression;
529 	vap->va_index = rap->a_hdr.a_index;
530 
531 	ddprintf(("type: 0x%x, index: %d", vap->va_type, vap->va_index));
532 
533 	vap->va_namelen = rap->a_hdr.a_namelen;
534 	if (rap->a_hdr.a_namelen) {
535 		wchar *unp = (wchar *) ((caddr_t) rap + rap->a_hdr.a_nameoff);
536 		ddprintf((", name:["));
537 		for (i = 0; i < vap->va_namelen; i++) {
538 			vap->va_name[i] = unp[i];
539 			ddprintf(("%c", vap->va_name[i]));
540 		}
541 		ddprintf(("]"));
542 	}
543 	if (vap->va_flag & NTFS_AF_INRUN) {
544 		ddprintf((", nonres."));
545 		vap->va_datalen = rap->a_nr.a_datalen;
546 		vap->va_allocated = rap->a_nr.a_allocated;
547 		vap->va_vcnstart = rap->a_nr.a_vcnstart;
548 		vap->va_vcnend = rap->a_nr.a_vcnend;
549 		vap->va_compressalg = rap->a_nr.a_compressalg;
550 		error = ntfs_runtovrun(&(vap->va_vruncn), &(vap->va_vruncl),
551 				       &(vap->va_vruncnt),
552 				       (caddr_t) rap + rap->a_nr.a_dataoff);
553 	} else {
554 		vap->va_compressalg = 0;
555 		ddprintf((", res."));
556 		vap->va_datalen = rap->a_r.a_datalen;
557 		vap->va_allocated = rap->a_r.a_datalen;
558 		vap->va_vcnstart = 0;
559 		vap->va_vcnend = ntfs_btocn(vap->va_allocated);
560 		vap->va_datap = kmalloc(vap->va_datalen, M_NTFSRDATA,
561 					M_WAITOK);
562 		memcpy(vap->va_datap, (caddr_t) rap + rap->a_r.a_dataoff,
563 		       rap->a_r.a_datalen);
564 	}
565 	ddprintf((", len: %d", vap->va_datalen));
566 
567 	if (error)
568 		kfree(vap, M_NTFSNTVATTR);
569 	else
570 		*rvapp = vap;
571 
572 	ddprintf(("\n"));
573 
574 	return (error);
575 }
576 
577 /*
578  * Expand run into more utilizable and more memory eating format.
579  */
580 int
581 ntfs_runtovrun(cn_t **rcnp, cn_t **rclp, u_long *rcntp, u_int8_t *run)
582 {
583 	u_int32_t       off;
584 	u_int32_t       sz, i;
585 	cn_t           *cn;
586 	cn_t           *cl;
587 	u_long		cnt;
588 	cn_t		prev;
589 	cn_t		tmp;
590 
591 	off = 0;
592 	cnt = 0;
593 	i = 0;
594 	while (run[off]) {
595 		off += (run[off] & 0xF) + ((run[off] >> 4) & 0xF) + 1;
596 		cnt++;
597 	}
598 	cn = kmalloc(cnt * sizeof(cn_t), M_NTFSRUN, M_WAITOK);
599 	cl = kmalloc(cnt * sizeof(cn_t), M_NTFSRUN, M_WAITOK);
600 
601 	off = 0;
602 	cnt = 0;
603 	prev = 0;
604 	while (run[off]) {
605 
606 		sz = run[off++];
607 		cl[cnt] = 0;
608 
609 		for (i = 0; i < (sz & 0xF); i++)
610 			cl[cnt] += (u_int32_t) run[off++] << (i << 3);
611 
612 		sz >>= 4;
613 		if (run[off + sz - 1] & 0x80) {
614 			tmp = ((u_int64_t) - 1) << (sz << 3);
615 			for (i = 0; i < sz; i++)
616 				tmp |= (u_int64_t) run[off++] << (i << 3);
617 		} else {
618 			tmp = 0;
619 			for (i = 0; i < sz; i++)
620 				tmp |= (u_int64_t) run[off++] << (i << 3);
621 		}
622 		if (tmp)
623 			prev = cn[cnt] = prev + tmp;
624 		else
625 			cn[cnt] = tmp;
626 
627 		cnt++;
628 	}
629 	*rcnp = cn;
630 	*rclp = cl;
631 	*rcntp = cnt;
632 	return (0);
633 }
634 
635 /*
636  * Compare unicode and ascii string case insens.
637  */
638 static int
639 ntfs_uastricmp(struct ntfsmount *ntmp, const wchar *ustr, size_t ustrlen,
640 	       const char *astr, size_t astrlen)
641 {
642 	int len;
643 	size_t i, j, mbstrlen = astrlen;
644 	int res;
645 	wchar wc;
646 
647 	if (ntmp->ntm_ic_l2u) {
648 		for (i = 0, j = 0; i < ustrlen && j < astrlen; i++, j++) {
649 			if (j < astrlen -1) {
650 				wc = (wchar)astr[j]<<8 | (astr[j+1]&0xFF);
651 				len = 2;
652 			} else {
653 				wc = (wchar)astr[j]<<8 & 0xFF00;
654 				len = 1;
655 			}
656 			res = ((int) NTFS_TOUPPER(ustr[i])) -
657 				((int)NTFS_TOUPPER(NTFS_82U(wc, &len)));
658 			j += len - 1;
659 			mbstrlen -= len - 1;
660 
661 			if (res)
662 				return res;
663 		}
664 	} else {
665 		/*
666 		 * We use NTFS_82U(NTFS_U28(c)) to get rid of unicode
667 		 * symbols not covered by translation table
668 		 */
669 		for (i = 0; i < ustrlen && i < astrlen; i++) {
670 			res = ((int) NTFS_TOUPPER(NTFS_82U(NTFS_U28(ustr[i]), &len))) -
671 				((int)NTFS_TOUPPER(NTFS_82U((wchar)astr[i], &len)));
672 			if (res)
673 				return res;
674 		}
675 	}
676 	return (ustrlen - mbstrlen);
677 }
678 
679 /*
680  * Compare unicode and ascii string case sens.
681  */
682 static int
683 ntfs_uastrcmp(struct ntfsmount *ntmp, const wchar *ustr, size_t ustrlen,
684 	      const char *astr, size_t astrlen)
685 {
686 	char u, l;
687 	size_t i, j, mbstrlen = astrlen;
688 	int res;
689 	wchar wc;
690 
691 	for (i = 0, j = 0; (i < ustrlen) && (j < astrlen); i++, j++) {
692 		res = 0;
693 		wc = NTFS_U28(ustr[i]);
694 		u = (char)(wc>>8);
695 		l = (char)wc;
696 		if (u != '\0' && j < astrlen -1) {
697 			res = (int) (u - astr[j++]);
698 			mbstrlen--;
699 		}
700 		res = (res<<8) + (int) (l - astr[j]);
701 		if (res)
702 			return res;
703 	}
704 	return (ustrlen - mbstrlen);
705 }
706 
707 /*
708  * Search fnode in ntnode, if not found allocate and preinitialize.
709  *
710  * ntnode should be locked on entry.
711  */
712 int
713 ntfs_fget(struct ntfsmount *ntmp, struct ntnode *ip, int attrtype,
714 	  char *attrname, struct fnode **fpp)
715 {
716 	struct fnode *fp;
717 
718 	dprintf(("ntfs_fget: ino: %"PRId64", attrtype: 0x%x, attrname: %s\n",
719 		ip->i_number,attrtype, attrname?attrname:""));
720 	*fpp = NULL;
721 	for (fp = ip->i_fnlist.lh_first; fp != NULL; fp = fp->f_fnlist.le_next){
722 		dprintf(("ntfs_fget: fnode: attrtype: %d, attrname: %s\n",
723 			fp->f_attrtype, fp->f_attrname?fp->f_attrname:""));
724 
725 		if ((attrtype == fp->f_attrtype) &&
726 		    ((!attrname && !fp->f_attrname) ||
727 		     (attrname && fp->f_attrname &&
728 		      !strcmp(attrname,fp->f_attrname)))){
729 			dprintf(("ntfs_fget: found existed: %p\n",fp));
730 			*fpp = fp;
731 		}
732 	}
733 
734 	if (*fpp)
735 		return (0);
736 
737 	fp = kmalloc(sizeof(struct fnode), M_NTFSFNODE, M_WAITOK | M_ZERO);
738 	dprintf(("ntfs_fget: allocating fnode: %p\n",fp));
739 
740 	fp->f_ip = ip;
741 	if (attrname) {
742 		fp->f_flag |= FN_AATTRNAME;
743 		fp->f_attrname = kmalloc(strlen(attrname) + 1, M_TEMP,
744 					 M_WAITOK);
745 		strcpy(fp->f_attrname, attrname);
746 	} else
747 		fp->f_attrname = NULL;
748 	fp->f_attrtype = attrtype;
749 
750 	ntfs_ntref(ip);
751 
752 	LIST_INSERT_HEAD(&ip->i_fnlist, fp, f_fnlist);
753 
754 	*fpp = fp;
755 
756 	return (0);
757 }
758 
759 /*
760  * Deallocate fnode, remove it from ntnode's fnode list.
761  *
762  * ntnode should be locked.
763  */
764 void
765 ntfs_frele(struct fnode *fp)
766 {
767 	struct ntnode *ip = FTONT(fp);
768 
769 	dprintf(("ntfs_frele: fnode: %p for %"PRId64": %p\n", fp, ip->i_number, ip));
770 
771 	dprintf(("ntfs_frele: deallocating fnode\n"));
772 	LIST_REMOVE(fp,f_fnlist);
773 	if (fp->f_flag & FN_AATTRNAME)
774 		kfree(fp->f_attrname, M_TEMP);
775 	if (fp->f_dirblbuf)
776 		kfree(fp->f_dirblbuf, M_NTFSDIR);
777 	kfree(fp, M_NTFSFNODE);
778 	ntfs_ntrele(ip);
779 }
780 
781 /*
782  * Lookup attribute name in format: [[:$ATTR_TYPE]:$ATTR_NAME],
783  * $ATTR_TYPE is searched in attrdefs read from $AttrDefs.
784  * If $ATTR_TYPE nott specifed, ATTR_A_DATA assumed.
785  */
786 static int
787 ntfs_ntlookupattr(struct ntfsmount *ntmp, const char *name, int namelen,
788 		  int *attrtype, char **attrname)
789 {
790 	const char *sys;
791 	size_t syslen, i;
792 	struct ntvattrdef *adp;
793 
794 	if (namelen == 0)
795 		return (0);
796 
797 	if (name[0] == '$') {
798 		sys = name;
799 		for (syslen = 0; syslen < namelen; syslen++) {
800 			if(sys[syslen] == ':') {
801 				name++;
802 				namelen--;
803 				break;
804 			}
805 		}
806 		name += syslen;
807 		namelen -= syslen;
808 
809 		adp = ntmp->ntm_ad;
810 		for (i = 0; i < ntmp->ntm_adnum; i++, adp++){
811 			if (syslen != adp->ad_namelen ||
812 			   strncmp(sys, adp->ad_name, syslen) != 0)
813 				continue;
814 
815 			*attrtype = adp->ad_type;
816 			goto out;
817 		}
818 		return (ENOENT);
819 	} else
820 		*attrtype = NTFS_A_DATA;
821 
822     out:
823 	if (namelen) {
824 		(*attrname) = kmalloc(namelen, M_TEMP, M_WAITOK);
825 		memcpy((*attrname), name, namelen);
826 		(*attrname)[namelen] = '\0';
827 	}
828 
829 	return (0);
830 }
831 
832 /*
833  * Lookup specifed node for filename, matching cnp,
834  * return fnode filled.
835  */
836 int
837 ntfs_ntlookupfile(struct ntfsmount *ntmp, struct vnode *vp,
838 		  struct componentname *cnp, struct vnode **vpp)
839 {
840 	struct fnode   *fp = VTOF(vp);
841 	struct ntnode  *ip = FTONT(fp);
842 	struct ntvattr *vap;	/* Root attribute */
843 	cn_t            cn;	/* VCN in current attribute */
844 	caddr_t         rdbuf;	/* Buffer to read directory's blocks  */
845 	u_int32_t       blsize;
846 	u_int32_t       rdsize;	/* Length of data to read from current block */
847 	struct attr_indexentry *iep;
848 	int             error, res, anamelen, fnamelen;
849 	const char     *fname,*aname;
850 	u_int32_t       aoff;
851 	int attrtype = NTFS_A_DATA;
852 	char *attrname = NULL;
853 	struct fnode   *nfp;
854 	struct vnode   *nvp;
855 	enum vtype	f_type;
856 
857 	error = ntfs_ntget(ip);
858 	if (error)
859 		return (error);
860 
861 	error = ntfs_ntvattrget(ntmp, ip, NTFS_A_INDXROOT, "$I30", 0, &vap);
862 	if (error || (vap->va_flag & NTFS_AF_INRUN))
863 		return (ENOTDIR);
864 
865 	blsize = vap->va_a_iroot->ir_size;
866 	rdsize = vap->va_datalen;
867 
868 	/*
869 	 * Divide file name into: foofilefoofilefoofile[:attrspec]
870 	 * Store like this:       fname:fnamelen       [aname:anamelen]
871 	 */
872 	fname = cnp->cn_nameptr;
873 	aname = NULL;
874 	anamelen = 0;
875 	for (fnamelen = 0; fnamelen < cnp->cn_namelen; fnamelen++)
876 		if(fname[fnamelen] == ':') {
877 			aname = fname + fnamelen + 1;
878 			anamelen = cnp->cn_namelen - fnamelen - 1;
879 			dprintf(("ntfs_ntlookupfile: %s (%d), attr: %s (%d)\n",
880 				fname, fnamelen, aname, anamelen));
881 			break;
882 		}
883 
884 	dprintf(("ntfs_ntlookupfile: blksz: %d, rdsz: %d\n", blsize, rdsize));
885 
886 	rdbuf = kmalloc(blsize, M_TEMP, M_WAITOK);
887 
888 	error = ntfs_readattr(ntmp, ip, NTFS_A_INDXROOT, "$I30",
889 			       0, rdsize, rdbuf, NULL);
890 	if (error)
891 		goto fail;
892 
893 	aoff = sizeof(struct attr_indexroot);
894 
895 	do {
896 		iep = (struct attr_indexentry *) (rdbuf + aoff);
897 
898 		for (; !(iep->ie_flag & NTFS_IEFLAG_LAST) && (rdsize > aoff);
899 			aoff += iep->reclen,
900 			iep = (struct attr_indexentry *) (rdbuf + aoff))
901 		{
902 			ddprintf(("scan: %d, %d\n",
903 				  (u_int32_t) iep->ie_number,
904 				  (u_int32_t) iep->ie_fnametype));
905 
906 			/* check the name - the case-insensitible check
907 			 * has to come first, to break from this for loop
908 			 * if needed, so we can dive correctly */
909 			res = NTFS_UASTRICMP(iep->ie_fname, iep->ie_fnamelen,
910 				fname, fnamelen);
911 			if (res > 0) break;
912 			if (res < 0) continue;
913 
914 			if (iep->ie_fnametype == 0 ||
915 			    !(ntmp->ntm_flag & NTFS_MFLAG_CASEINS))
916 			{
917 				res = NTFS_UASTRCMP(iep->ie_fname,
918 					iep->ie_fnamelen, fname, fnamelen);
919 				if (res != 0) continue;
920 			}
921 
922 			if (aname) {
923 				error = ntfs_ntlookupattr(ntmp,
924 					aname, anamelen,
925 					&attrtype, &attrname);
926 				if (error)
927 					goto fail;
928 			}
929 
930 			/* Check if we've found ourself */
931 			if ((iep->ie_number == ip->i_number) &&
932 			    (attrtype == fp->f_attrtype) &&
933 			    ((!attrname && !fp->f_attrname) ||
934 			     (attrname && fp->f_attrname &&
935 			      !strcmp(attrname, fp->f_attrname))))
936 			{
937 				vref(vp);
938 				*vpp = vp;
939 				error = 0;
940 				goto fail;
941 			}
942 
943 			/* vget node, but don't load it */
944 			error = ntfs_vgetex(ntmp->ntm_mountp,
945 				   iep->ie_number, attrtype, attrname,
946 				   LK_EXCLUSIVE, VG_DONTLOADIN | VG_DONTVALIDFN,
947 				   curthread, &nvp);
948 
949 			/* free the buffer returned by ntfs_ntlookupattr() */
950 			if (attrname) {
951 				kfree(attrname, M_TEMP);
952 				attrname = NULL;
953 			}
954 
955 			if (error)
956 				goto fail;
957 
958 			nfp = VTOF(nvp);
959 
960 			if (nfp->f_flag & FN_VALID) {
961 				*vpp = nvp;
962 				goto fail;
963 			}
964 
965 			nfp->f_fflag = iep->ie_fflag;
966 			nfp->f_pnumber = iep->ie_fpnumber;
967 			nfp->f_times = iep->ie_ftimes;
968 
969 			if((nfp->f_fflag & NTFS_FFLAG_DIR) &&
970 			   (nfp->f_attrtype == NTFS_A_DATA) &&
971 			   (nfp->f_attrname == NULL))
972 				f_type = VDIR;
973 			else
974 				f_type = VREG;
975 
976 			nvp->v_type = f_type;
977 
978 			if ((nfp->f_attrtype == NTFS_A_DATA) &&
979 			    (nfp->f_attrname == NULL))
980 			{
981 				/* Opening default attribute */
982 				nfp->f_size = iep->ie_fsize;
983 				nfp->f_allocated = iep->ie_fallocated;
984 				nfp->f_flag |= FN_PRELOADED;
985 			} else {
986 				error = ntfs_filesize(ntmp, nfp,
987 					    &nfp->f_size, &nfp->f_allocated);
988 				if (error) {
989 					vput(nvp);
990 					goto fail;
991 				}
992 			}
993 			nfp->f_flag &= ~FN_VALID;
994 
995 			/*
996 			 * Normal files use the buffer cache
997 			 */
998 			if (nvp->v_type == VREG)
999 				vinitvmio(nvp, nfp->f_size, PAGE_SIZE, -1);
1000 			*vpp = nvp;
1001 			goto fail;
1002 		}
1003 
1004 		/* Dive if possible */
1005 		if (iep->ie_flag & NTFS_IEFLAG_SUBNODE) {
1006 			dprintf(("ntfs_ntlookupfile: diving\n"));
1007 
1008 			cn = *(cn_t *) (rdbuf + aoff +
1009 					iep->reclen - sizeof(cn_t));
1010 			rdsize = blsize;
1011 
1012 			error = ntfs_readattr(ntmp, ip, NTFS_A_INDX, "$I30",
1013 					ntfs_cntob(cn), rdsize, rdbuf, NULL);
1014 			if (error)
1015 				goto fail;
1016 
1017 			error = ntfs_procfixups(ntmp, NTFS_INDXMAGIC,
1018 						rdbuf, rdsize);
1019 			if (error)
1020 				goto fail;
1021 
1022 			aoff = (((struct attr_indexalloc *) rdbuf)->ia_hdrsize +
1023 				0x18);
1024 		} else {
1025 			dprintf(("ntfs_ntlookupfile: nowhere to dive :-(\n"));
1026 			error = ENOENT;
1027 			break;
1028 		}
1029 	} while (1);
1030 
1031 	dprintf(("finish\n"));
1032 
1033 fail:
1034 	if (attrname) kfree(attrname, M_TEMP);
1035 	ntfs_ntvattrrele(vap);
1036 	ntfs_ntput(ip);
1037 	kfree(rdbuf, M_TEMP);
1038 	return (error);
1039 }
1040 
1041 /*
1042  * Check if name type is permitted to show.
1043  */
1044 int
1045 ntfs_isnamepermitted(struct ntfsmount *ntmp, struct attr_indexentry *iep)
1046 {
1047 	if (ntmp->ntm_flag & NTFS_MFLAG_ALLNAMES)
1048 		return 1;
1049 
1050 	switch (iep->ie_fnametype) {
1051 	case 2:
1052 		ddprintf(("ntfs_isnamepermitted: skipped DOS name\n"));
1053 		return 0;
1054 	case 0: case 1: case 3:
1055 		return 1;
1056 	default:
1057 		kprintf("ntfs_isnamepermitted: " \
1058 		       "WARNING! Unknown file name type: %d\n",
1059 		       iep->ie_fnametype);
1060 		break;
1061 	}
1062 	return 0;
1063 }
1064 
1065 /*
1066  * Read ntfs dir like stream of attr_indexentry, not like btree of them.
1067  * This is done by scaning $BITMAP:$I30 for busy clusters and reading them.
1068  * Ofcouse $INDEX_ROOT:$I30 is read before. Last read values are stored in
1069  * fnode, so we can skip toward record number num almost immediatly.
1070  * Anyway this is rather slow routine. The problem is that we don't know
1071  * how many records are there in $INDEX_ALLOCATION:$I30 block.
1072  */
1073 int
1074 ntfs_ntreaddir(struct ntfsmount *ntmp, struct fnode *fp,
1075 	       u_int32_t num, struct attr_indexentry **riepp)
1076 {
1077 	struct ntnode  *ip = FTONT(fp);
1078 	struct ntvattr *vap = NULL;	/* IndexRoot attribute */
1079 	struct ntvattr *bmvap = NULL;	/* BitMap attribute */
1080 	struct ntvattr *iavap = NULL;	/* IndexAllocation attribute */
1081 	caddr_t         rdbuf;		/* Buffer to read directory's blocks  */
1082 	u_char         *bmp = NULL;	/* Bitmap */
1083 	u_int32_t       blsize;		/* Index allocation size (2048) */
1084 	u_int32_t       rdsize;		/* Length of data to read */
1085 	u_int32_t       attrnum;	/* Current attribute type */
1086 	u_int32_t       cpbl = 1;	/* Clusters per directory block */
1087 	u_int32_t       blnum;
1088 	struct attr_indexentry *iep;
1089 	int             error = ENOENT;
1090 	u_int32_t       aoff, cnum;
1091 
1092 	dprintf(("ntfs_ntreaddir: read ino: %"PRId64", num: %d\n", ip->i_number, num));
1093 	error = ntfs_ntget(ip);
1094 	if (error)
1095 		return (error);
1096 
1097 	error = ntfs_ntvattrget(ntmp, ip, NTFS_A_INDXROOT, "$I30", 0, &vap);
1098 	if (error)
1099 		return (ENOTDIR);
1100 
1101 	if (fp->f_dirblbuf == NULL) {
1102 		fp->f_dirblsz = vap->va_a_iroot->ir_size;
1103 		fp->f_dirblbuf = kmalloc(max(vap->va_datalen, fp->f_dirblsz),
1104 					 M_NTFSDIR, M_WAITOK);
1105 	}
1106 
1107 	blsize = fp->f_dirblsz;
1108 	rdbuf = fp->f_dirblbuf;
1109 
1110 	dprintf(("ntfs_ntreaddir: rdbuf: 0x%p, blsize: %d\n", rdbuf, blsize));
1111 
1112 	if (vap->va_a_iroot->ir_flag & NTFS_IRFLAG_INDXALLOC) {
1113 		error = ntfs_ntvattrget(ntmp, ip, NTFS_A_INDXBITMAP, "$I30",
1114 					0, &bmvap);
1115 		if (error) {
1116 			error = ENOTDIR;
1117 			goto fail;
1118 		}
1119 		bmp = kmalloc(bmvap->va_datalen, M_TEMP, M_WAITOK);
1120 		error = ntfs_readattr(ntmp, ip, NTFS_A_INDXBITMAP, "$I30", 0,
1121 				       bmvap->va_datalen, bmp, NULL);
1122 		if (error)
1123 			goto fail;
1124 
1125 		error = ntfs_ntvattrget(ntmp, ip, NTFS_A_INDX, "$I30",
1126 					0, &iavap);
1127 		if (error) {
1128 			error = ENOTDIR;
1129 			goto fail;
1130 		}
1131 		cpbl = ntfs_btocn(blsize + ntfs_cntob(1) - 1);
1132 		dprintf(("ntfs_ntreaddir: indexalloc: %d, cpbl: %d\n",
1133 			 iavap->va_datalen, cpbl));
1134 	} else {
1135 		dprintf(("ntfs_ntreadidir: w/o BitMap and IndexAllocation\n"));
1136 		iavap = bmvap = NULL;
1137 		bmp = NULL;
1138 	}
1139 
1140 	/* Try use previous values */
1141 	if ((fp->f_lastdnum < num) && (fp->f_lastdnum != 0)) {
1142 		attrnum = fp->f_lastdattr;
1143 		aoff = fp->f_lastdoff;
1144 		blnum = fp->f_lastdblnum;
1145 		cnum = fp->f_lastdnum;
1146 	} else {
1147 		attrnum = NTFS_A_INDXROOT;
1148 		aoff = sizeof(struct attr_indexroot);
1149 		blnum = 0;
1150 		cnum = 0;
1151 	}
1152 
1153 	do {
1154 		dprintf(("ntfs_ntreaddir: scan: 0x%x, %d, %d, %d, %d\n",
1155 			 attrnum, blnum, cnum, num, aoff));
1156 		rdsize = (attrnum == NTFS_A_INDXROOT) ? vap->va_datalen : blsize;
1157 		error = ntfs_readattr(ntmp, ip, attrnum, "$I30",
1158 				ntfs_cntob(blnum * cpbl), rdsize, rdbuf, NULL);
1159 		if (error)
1160 			goto fail;
1161 
1162 		if (attrnum == NTFS_A_INDX) {
1163 			error = ntfs_procfixups(ntmp, NTFS_INDXMAGIC,
1164 						rdbuf, rdsize);
1165 			if (error)
1166 				goto fail;
1167 		}
1168 		if (aoff == 0)
1169 			aoff = (attrnum == NTFS_A_INDX) ?
1170 				(0x18 + ((struct attr_indexalloc *) rdbuf)->ia_hdrsize) :
1171 				sizeof(struct attr_indexroot);
1172 
1173 		iep = (struct attr_indexentry *) (rdbuf + aoff);
1174 		for (; !(iep->ie_flag & NTFS_IEFLAG_LAST) && (rdsize > aoff);
1175 			aoff += iep->reclen,
1176 			iep = (struct attr_indexentry *) (rdbuf + aoff))
1177 		{
1178 			if (!ntfs_isnamepermitted(ntmp, iep)) continue;
1179 
1180 			if (cnum >= num) {
1181 				fp->f_lastdnum = cnum;
1182 				fp->f_lastdoff = aoff;
1183 				fp->f_lastdblnum = blnum;
1184 				fp->f_lastdattr = attrnum;
1185 
1186 				*riepp = iep;
1187 
1188 				error = 0;
1189 				goto fail;
1190 			}
1191 			cnum++;
1192 		}
1193 
1194 		if (iavap) {
1195 			if (attrnum == NTFS_A_INDXROOT)
1196 				blnum = 0;
1197 			else
1198 				blnum++;
1199 
1200 			while (ntfs_cntob(blnum * cpbl) < iavap->va_datalen) {
1201 				if (bmp[blnum >> 3] & (1 << (blnum & 3)))
1202 					break;
1203 				blnum++;
1204 			}
1205 
1206 			attrnum = NTFS_A_INDX;
1207 			aoff = 0;
1208 			if (ntfs_cntob(blnum * cpbl) >= iavap->va_datalen)
1209 				break;
1210 			dprintf(("ntfs_ntreaddir: blnum: %d\n", blnum));
1211 		}
1212 	} while (iavap);
1213 
1214 	*riepp = NULL;
1215 	fp->f_lastdnum = 0;
1216 
1217 fail:
1218 	if (vap)
1219 		ntfs_ntvattrrele(vap);
1220 	if (bmvap)
1221 		ntfs_ntvattrrele(bmvap);
1222 	if (iavap)
1223 		ntfs_ntvattrrele(iavap);
1224 	if (bmp)
1225 		kfree(bmp, M_TEMP);
1226 	ntfs_ntput(ip);
1227 	return (error);
1228 }
1229 
1230 /*
1231  * Convert NTFS times that are in 100 ns units and begins from
1232  * 1601 Jan 1 into unix times.
1233  */
1234 struct timespec
1235 ntfs_nttimetounix(u_int64_t nt)
1236 {
1237 	struct timespec t;
1238 
1239 	/* WindowNT times are in 100 ns and from 1601 Jan 1 */
1240 	t.tv_nsec = (nt % (1000 * 1000 * 10)) * 100;
1241 	t.tv_sec = nt / (1000 * 1000 * 10) -
1242 		369LL * 365LL * 24LL * 60LL * 60LL -
1243 		89LL * 1LL * 24LL * 60LL * 60LL;
1244 	return (t);
1245 }
1246 
1247 /*
1248  * Get file times from NTFS_A_NAME attribute.
1249  */
1250 int
1251 ntfs_times(struct ntfsmount *ntmp, struct ntnode *ip, ntfs_times_t *tm)
1252 {
1253 	struct ntvattr *vap;
1254 	int             error;
1255 
1256 	dprintf(("ntfs_times: ino: %"PRId64"...\n", ip->i_number));
1257 
1258 	error = ntfs_ntget(ip);
1259 	if (error)
1260 		return (error);
1261 
1262 	error = ntfs_ntvattrget(ntmp, ip, NTFS_A_NAME, NULL, 0, &vap);
1263 	if (error) {
1264 		ntfs_ntput(ip);
1265 		return (error);
1266 	}
1267 	*tm = vap->va_a_name->n_times;
1268 	ntfs_ntvattrrele(vap);
1269 	ntfs_ntput(ip);
1270 
1271 	return (0);
1272 }
1273 
1274 /*
1275  * Get file sizes from corresponding attribute.
1276  *
1277  * ntnode under fnode should be locked.
1278  */
1279 int
1280 ntfs_filesize(struct ntfsmount *ntmp, struct fnode *fp, u_int64_t *size,
1281 	      u_int64_t *bytes)
1282 {
1283 	struct ntvattr *vap;
1284 	struct ntnode *ip = FTONT(fp);
1285 	u_int64_t       sz, bn;
1286 	int             error;
1287 
1288 	dprintf(("ntfs_filesize: ino: %"PRId64"\n", ip->i_number));
1289 
1290 	error = ntfs_ntvattrget(ntmp, ip,
1291 		fp->f_attrtype, fp->f_attrname, 0, &vap);
1292 	if (error)
1293 		return (error);
1294 
1295 	bn = vap->va_allocated;
1296 	sz = vap->va_datalen;
1297 
1298 	dprintf(("ntfs_filesize: %d bytes (%d bytes allocated)\n",
1299 		(u_int32_t) sz, (u_int32_t) bn));
1300 
1301 	if (size)
1302 		*size = sz;
1303 	if (bytes)
1304 		*bytes = bn;
1305 
1306 	ntfs_ntvattrrele(vap);
1307 
1308 	return (0);
1309 }
1310 
1311 /*
1312  * This is one of write routine.
1313  */
1314 int
1315 ntfs_writeattr_plain(struct ntfsmount *ntmp, struct ntnode *ip,
1316 		     u_int32_t attrnum, char *attrname,	off_t roff,
1317 		     size_t rsize, void *rdata,	size_t *initp,
1318 		     struct uio *uio)
1319 {
1320 	size_t          init;
1321 	int             error = 0;
1322 	off_t           off = roff, left = rsize, towrite;
1323 	caddr_t         data = rdata;
1324 	struct ntvattr *vap;
1325 	*initp = 0;
1326 
1327 	while (left) {
1328 		error = ntfs_ntvattrget(ntmp, ip, attrnum, attrname,
1329 					ntfs_btocn(off), &vap);
1330 		if (error)
1331 			return (error);
1332 		towrite = min(left, ntfs_cntob(vap->va_vcnend + 1) - off);
1333 		ddprintf(("ntfs_writeattr_plain: o: %d, s: %d (%d - %d)\n",
1334 			 (u_int32_t) off, (u_int32_t) towrite,
1335 			 (u_int32_t) vap->va_vcnstart,
1336 			 (u_int32_t) vap->va_vcnend));
1337 		error = ntfs_writentvattr_plain(ntmp, ip, vap,
1338 					 off - ntfs_cntob(vap->va_vcnstart),
1339 					 towrite, data, &init, uio);
1340 		if (error) {
1341 			kprintf("ntfs_writeattr_plain: " \
1342 			       "ntfs_writentvattr_plain failed: o: %d, s: %d\n",
1343 			       (u_int32_t) off, (u_int32_t) towrite);
1344 			kprintf("ntfs_writeattr_plain: attrib: %d - %d\n",
1345 			       (u_int32_t) vap->va_vcnstart,
1346 			       (u_int32_t) vap->va_vcnend);
1347 			ntfs_ntvattrrele(vap);
1348 			break;
1349 		}
1350 		ntfs_ntvattrrele(vap);
1351 		left -= towrite;
1352 		off += towrite;
1353 		data = data + towrite;
1354 		*initp += init;
1355 	}
1356 
1357 	return (error);
1358 }
1359 
1360 /*
1361  * This is one of write routine.
1362  *
1363  * ntnode should be locked.
1364  */
1365 int
1366 ntfs_writentvattr_plain(struct ntfsmount *ntmp,	struct ntnode *ip,
1367 			struct ntvattr *vap, off_t roff, size_t rsize,
1368 			void *rdata, size_t *initp, struct uio *uio)
1369 {
1370 	int             error = 0;
1371 	int             off;
1372 	int             cnt;
1373 	cn_t            ccn, ccl, cn, left, cl;
1374 	caddr_t         data = rdata;
1375 	struct buf     *bp;
1376 	size_t          tocopy;
1377 
1378 	*initp = 0;
1379 
1380 	if ((vap->va_flag & NTFS_AF_INRUN) == 0) {
1381 		kprintf("ntfs_writevattr_plain: CAN'T WRITE RES. ATTRIBUTE\n");
1382 		return ENOTTY;
1383 	}
1384 
1385 	ddprintf(("ntfs_writentvattr_plain: data in run: %ld chains\n",
1386 		 vap->va_vruncnt));
1387 
1388 	off = roff;
1389 	left = rsize;
1390 	ccl = 0;
1391 	ccn = 0;
1392 	cnt = 0;
1393 	for (; left && (cnt < vap->va_vruncnt); cnt++) {
1394 		ccn = vap->va_vruncn[cnt];
1395 		ccl = vap->va_vruncl[cnt];
1396 
1397 		ddprintf(("ntfs_writentvattr_plain: " \
1398 			 "left %d, cn: 0x%x, cl: %d, off: %d\n", \
1399 			 (u_int32_t) left, (u_int32_t) ccn, \
1400 			 (u_int32_t) ccl, (u_int32_t) off));
1401 
1402 		if (ntfs_cntob(ccl) < off) {
1403 			off -= ntfs_cntob(ccl);
1404 			cnt++;
1405 			continue;
1406 		}
1407 		if (!ccn && ip->i_number != NTFS_BOOTINO)
1408 			continue; /* XXX */
1409 
1410 		ccl -= ntfs_btocn(off);
1411 		cn = ccn + ntfs_btocn(off);
1412 		off = ntfs_btocnoff(off);
1413 
1414 		while (left && ccl) {
1415 			/*
1416 			 * Always read and write single clusters at a time -
1417 			 * we need to avoid requesting differently-sized
1418 			 * blocks at the same disk offsets to avoid
1419 			 * confusing the buffer cache.
1420 			 */
1421 			tocopy = min(left, ntfs_cntob(1) - off);
1422 			cl = ntfs_btocl(tocopy + off);
1423 			KASSERT(cl == 1 && tocopy <= ntfs_cntob(1),
1424 			    ("single cluster limit mistake"));
1425 			ddprintf(("ntfs_writentvattr_plain: write: " \
1426 				"cn: 0x%x cl: %d, off: %d len: %d, left: %d\n",
1427 				(u_int32_t) cn, (u_int32_t) cl,
1428 				(u_int32_t) off, (u_int32_t) tocopy,
1429 				(u_int32_t) left));
1430 			if (off == 0 && tocopy == ntfs_cntob(cl) &&
1431 			    uio->uio_segflg != UIO_NOCOPY) {
1432 				bp = getblk(ntmp->ntm_devvp, ntfs_cntodoff(cn),
1433 					    ntfs_cntob(cl), 0, 0);
1434 				clrbuf(bp);
1435 			} else {
1436 				error = bread(ntmp->ntm_devvp,
1437 					      ntfs_cntodoff(cn),
1438 					      ntfs_cntob(cl), &bp);
1439 				if (error) {
1440 					brelse(bp);
1441 					return (error);
1442 				}
1443 			}
1444 			if (uio)
1445 				uiomovebp(bp, bp->b_data + off, tocopy, uio);
1446 			else
1447 				memcpy(bp->b_data + off, data, tocopy);
1448 			bawrite(bp);
1449 			data = data + tocopy;
1450 			*initp += tocopy;
1451 			off = 0;
1452 			left -= tocopy;
1453 			cn += cl;
1454 			ccl -= cl;
1455 		}
1456 	}
1457 
1458 	if (left) {
1459 		kprintf("ntfs_writentvattr_plain: POSSIBLE RUN ERROR\n");
1460 		error = EINVAL;
1461 	}
1462 
1463 	return (error);
1464 }
1465 
1466 /*
1467  * This is one of read routines.
1468  *
1469  * ntnode should be locked.
1470  */
1471 int
1472 ntfs_readntvattr_plain(struct ntfsmount *ntmp, struct ntnode *ip,
1473 		       struct ntvattr *vap, off_t roff, size_t rsize,
1474 		       void *rdata, size_t *initp, struct uio *uio)
1475 {
1476 	int             error = 0;
1477 	int             off;
1478 
1479 	*initp = 0;
1480 	if (vap->va_flag & NTFS_AF_INRUN) {
1481 		int             cnt;
1482 		cn_t            ccn, ccl, cn, left, cl;
1483 		caddr_t         data = rdata;
1484 		struct buf     *bp;
1485 		size_t          tocopy;
1486 
1487 		ddprintf(("ntfs_readntvattr_plain: data in run: %ld chains\n",
1488 			 vap->va_vruncnt));
1489 
1490 		off = roff;
1491 		left = rsize;
1492 		ccl = 0;
1493 		ccn = 0;
1494 		cnt = 0;
1495 		while (left && (cnt < vap->va_vruncnt)) {
1496 			ccn = vap->va_vruncn[cnt];
1497 			ccl = vap->va_vruncl[cnt];
1498 
1499 			ddprintf(("ntfs_readntvattr_plain: " \
1500 				 "left %d, cn: 0x%x, cl: %d, off: %d\n", \
1501 				 (u_int32_t) left, (u_int32_t) ccn, \
1502 				 (u_int32_t) ccl, (u_int32_t) off));
1503 
1504 			if (ntfs_cntob(ccl) < off) {
1505 				off -= ntfs_cntob(ccl);
1506 				cnt++;
1507 				continue;
1508 			}
1509 			if (ccn || ip->i_number == NTFS_BOOTINO) {
1510 				ccl -= ntfs_btocn(off);
1511 				cn = ccn + ntfs_btocn(off);
1512 				off = ntfs_btocnoff(off);
1513 
1514 				while (left && ccl) {
1515 					tocopy = min(left,
1516 						  min(ntfs_cntob(ccl) - off,
1517 						      MAXBSIZE - off));
1518 					cl = ntfs_btocl(tocopy + off);
1519 
1520 					/*
1521 					 * Always read single clusters at a
1522 					 * time - we need to avoid reading
1523 					 * differently-sized blocks at the
1524 					 * same disk offsets to avoid
1525 					 * confusing the buffer cache.
1526 					 */
1527 					tocopy = min(left,
1528 					    ntfs_cntob(1) - off);
1529 					cl = ntfs_btocl(tocopy + off);
1530 					KASSERT(cl == 1 &&
1531 					    tocopy <= ntfs_cntob(1),
1532 					    ("single cluster limit mistake"));
1533 
1534 					ddprintf(("ntfs_readntvattr_plain: " \
1535 						"read: cn: 0x%x cl: %d, " \
1536 						"off: %d len: %d, left: %d\n",
1537 						(u_int32_t) cn,
1538 						(u_int32_t) cl,
1539 						(u_int32_t) off,
1540 						(u_int32_t) tocopy,
1541 						(u_int32_t) left));
1542 					error = bread(ntmp->ntm_devvp,
1543 						      ntfs_cntodoff(cn),
1544 						      ntfs_cntob(cl),
1545 						      &bp);
1546 					if (error) {
1547 						brelse(bp);
1548 						return (error);
1549 					}
1550 					if (uio) {
1551 						uiomovebp(bp, bp->b_data + off,
1552 							tocopy, uio);
1553 					} else {
1554 						memcpy(data, bp->b_data + off,
1555 							tocopy);
1556 					}
1557 					brelse(bp);
1558 					data = data + tocopy;
1559 					*initp += tocopy;
1560 					off = 0;
1561 					left -= tocopy;
1562 					cn += cl;
1563 					ccl -= cl;
1564 				}
1565 			} else {
1566 				tocopy = min(left, ntfs_cntob(ccl) - off);
1567 				ddprintf(("ntfs_readntvattr_plain: "
1568 					"hole: ccn: 0x%x ccl: %d, off: %d, " \
1569 					" len: %d, left: %d\n",
1570 					(u_int32_t) ccn, (u_int32_t) ccl,
1571 					(u_int32_t) off, (u_int32_t) tocopy,
1572 					(u_int32_t) left));
1573 				left -= tocopy;
1574 				off = 0;
1575 				if (uio) {
1576 					size_t remains = tocopy;
1577 					for(; remains; remains--)
1578 						uiomove("", 1, uio);
1579 				} else
1580 					bzero(data, tocopy);
1581 				data = data + tocopy;
1582 			}
1583 			cnt++;
1584 		}
1585 		if (left) {
1586 			kprintf("ntfs_readntvattr_plain: POSSIBLE RUN ERROR\n");
1587 			error = E2BIG;
1588 		}
1589 	} else {
1590 		ddprintf(("ntfs_readnvattr_plain: data is in mft record\n"));
1591 		if (uio)
1592 			uiomove(vap->va_datap + roff, rsize, uio);
1593 		else
1594 			memcpy(rdata, vap->va_datap + roff, rsize);
1595 		*initp += rsize;
1596 	}
1597 
1598 	return (error);
1599 }
1600 
1601 /*
1602  * This is one of read routines.
1603  */
1604 int
1605 ntfs_readattr_plain(struct ntfsmount *ntmp, struct ntnode *ip,
1606 		    u_int32_t attrnum, char *attrname, off_t roff,
1607 		    size_t rsize, void *rdata, size_t * initp,
1608 		    struct uio *uio)
1609 {
1610 	size_t          init;
1611 	int             error = 0;
1612 	off_t           off = roff, left = rsize, toread;
1613 	caddr_t         data = rdata;
1614 	struct ntvattr *vap;
1615 	*initp = 0;
1616 
1617 	while (left) {
1618 		error = ntfs_ntvattrget(ntmp, ip, attrnum, attrname,
1619 					ntfs_btocn(off), &vap);
1620 		if (error)
1621 			return (error);
1622 		toread = min(left, ntfs_cntob(vap->va_vcnend + 1) - off);
1623 		ddprintf(("ntfs_readattr_plain: o: %d, s: %d (%d - %d)\n",
1624 			 (u_int32_t) off, (u_int32_t) toread,
1625 			 (u_int32_t) vap->va_vcnstart,
1626 			 (u_int32_t) vap->va_vcnend));
1627 		error = ntfs_readntvattr_plain(ntmp, ip, vap,
1628 					 off - ntfs_cntob(vap->va_vcnstart),
1629 					 toread, data, &init, uio);
1630 		if (error) {
1631 			kprintf("ntfs_readattr_plain: " \
1632 			       "ntfs_readntvattr_plain failed: o: %d, s: %d\n",
1633 			       (u_int32_t) off, (u_int32_t) toread);
1634 			kprintf("ntfs_readattr_plain: attrib: %d - %d\n",
1635 			       (u_int32_t) vap->va_vcnstart,
1636 			       (u_int32_t) vap->va_vcnend);
1637 			ntfs_ntvattrrele(vap);
1638 			break;
1639 		}
1640 		ntfs_ntvattrrele(vap);
1641 		left -= toread;
1642 		off += toread;
1643 		data = data + toread;
1644 		*initp += init;
1645 	}
1646 
1647 	return (error);
1648 }
1649 
1650 /*
1651  * This is one of read routines.
1652  */
1653 int
1654 ntfs_readattr(struct ntfsmount *ntmp, struct ntnode *ip, u_int32_t attrnum,
1655 	      char *attrname, off_t roff, size_t rsize, void *rdata,
1656 	      struct uio *uio)
1657 {
1658 	int             error = 0;
1659 	struct ntvattr *vap;
1660 	size_t          init;
1661 
1662 	ddprintf(("ntfs_readattr: reading %"PRId64": 0x%x, from %d size %d bytes\n",
1663 	       ip->i_number, attrnum, (u_int32_t) roff, (u_int32_t) rsize));
1664 
1665 	error = ntfs_ntvattrget(ntmp, ip, attrnum, attrname, 0, &vap);
1666 	if (error)
1667 		return (error);
1668 
1669 	if ((roff > vap->va_datalen) ||
1670 	    (roff + rsize > vap->va_datalen)) {
1671 		ddprintf(("ntfs_readattr: offset too big\n"));
1672 		ntfs_ntvattrrele(vap);
1673 		return (E2BIG);
1674 	}
1675 	if (vap->va_compression && vap->va_compressalg) {
1676 		u_int8_t       *cup;
1677 		u_int8_t       *uup;
1678 		off_t           off, left = rsize, tocopy;
1679 		caddr_t         data = rdata;
1680 		cn_t            cn;
1681 
1682 		ddprintf(("ntfs_ntreadattr: compression: %d\n",
1683 			 vap->va_compressalg));
1684 
1685 		cup = kmalloc(ntfs_cntob(NTFS_COMPUNIT_CL), M_NTFSDECOMP,
1686 			      M_WAITOK);
1687 		uup = kmalloc(ntfs_cntob(NTFS_COMPUNIT_CL), M_NTFSDECOMP,
1688 			      M_WAITOK);
1689 
1690 		cn = (ntfs_btocn(roff)) & (~(NTFS_COMPUNIT_CL - 1));
1691 		off = roff - ntfs_cntob(cn);
1692 
1693 		while (left) {
1694 			error = ntfs_readattr_plain(ntmp, ip, attrnum,
1695 						  attrname, ntfs_cntob(cn),
1696 						  ntfs_cntob(NTFS_COMPUNIT_CL),
1697 						  cup, &init, NULL);
1698 			if (error)
1699 				break;
1700 
1701 			tocopy = min(left, ntfs_cntob(NTFS_COMPUNIT_CL) - off);
1702 
1703 			if (init == ntfs_cntob(NTFS_COMPUNIT_CL)) {
1704 				if (uio)
1705 					uiomove(cup + off, tocopy, uio);
1706 				else
1707 					memcpy(data, cup + off, tocopy);
1708 			} else if (init == 0) {
1709 				if (uio) {
1710 					size_t remains = tocopy;
1711 					for(; remains; remains--)
1712 						uiomove("", 1, uio);
1713 				}
1714 				else
1715 					bzero(data, tocopy);
1716 			} else {
1717 				error = ntfs_uncompunit(ntmp, uup, cup);
1718 				if (error)
1719 					break;
1720 				if (uio)
1721 					uiomove(uup + off, tocopy, uio);
1722 				else
1723 					memcpy(data, uup + off, tocopy);
1724 			}
1725 
1726 			left -= tocopy;
1727 			data = data + tocopy;
1728 			off += tocopy - ntfs_cntob(NTFS_COMPUNIT_CL);
1729 			cn += NTFS_COMPUNIT_CL;
1730 		}
1731 
1732 		kfree(uup, M_NTFSDECOMP);
1733 		kfree(cup, M_NTFSDECOMP);
1734 	} else
1735 		error = ntfs_readattr_plain(ntmp, ip, attrnum, attrname,
1736 					     roff, rsize, rdata, &init, uio);
1737 	ntfs_ntvattrrele(vap);
1738 	return (error);
1739 }
1740 
1741 #if 0 /* UNUSED */
1742 int
1743 ntfs_parserun(cn_t *cn, cn_t *cl, u_int8_t *run, u_long len, u_long *off)
1744 {
1745 	u_int8_t        sz;
1746 	int             i;
1747 
1748 	if (NULL == run) {
1749 		kprintf("ntfs_parsetun: run == NULL\n");
1750 		return (EINVAL);
1751 	}
1752 	sz = run[(*off)++];
1753 	if (0 == sz) {
1754 		kprintf("ntfs_parserun: trying to go out of run\n");
1755 		return (E2BIG);
1756 	}
1757 	*cl = 0;
1758 	if ((sz & 0xF) > 8 || (*off) + (sz & 0xF) > len) {
1759 		kprintf("ntfs_parserun: " \
1760 		       "bad run: length too big: sz: 0x%02x (%ld < %ld + sz)\n",
1761 		       sz, len, *off);
1762 		return (EINVAL);
1763 	}
1764 	for (i = 0; i < (sz & 0xF); i++)
1765 		*cl += (u_int32_t) run[(*off)++] << (i << 3);
1766 
1767 	sz >>= 4;
1768 	if ((sz & 0xF) > 8 || (*off) + (sz & 0xF) > len) {
1769 		kprintf("ntfs_parserun: " \
1770 		       "bad run: length too big: sz: 0x%02x (%ld < %ld + sz)\n",
1771 		       sz, len, *off);
1772 		return (EINVAL);
1773 	}
1774 	for (i = 0; i < (sz & 0xF); i++)
1775 		*cn += (u_int32_t) run[(*off)++] << (i << 3);
1776 
1777 	return (0);
1778 }
1779 #endif
1780 
1781 /*
1782  * Process fixup routine on given buffer.
1783  */
1784 int
1785 ntfs_procfixups(struct ntfsmount *ntmp, u_int32_t magic, caddr_t buf,
1786 		size_t len)
1787 {
1788 	struct fixuphdr *fhp = (struct fixuphdr *) buf;
1789 	int             i;
1790 	u_int16_t       fixup;
1791 	u_int16_t      *fxp;
1792 	u_int16_t      *cfxp;
1793 
1794 	if (fhp->fh_magic != magic) {
1795 		kprintf("ntfs_procfixups: magic doesn't match: %08x != %08x\n",
1796 		       fhp->fh_magic, magic);
1797 		return (EINVAL);
1798 	}
1799 	if ((fhp->fh_fnum - 1) * ntmp->ntm_bps != len) {
1800 		kprintf("ntfs_procfixups: " \
1801 		       "bad fixups number: %d for %ld bytes block\n",
1802 		       fhp->fh_fnum, (long)len);	/* XXX kprintf kludge */
1803 		return (EINVAL);
1804 	}
1805 	if (fhp->fh_foff >= ntmp->ntm_spc * ntmp->ntm_mftrecsz * ntmp->ntm_bps) {
1806 		kprintf("ntfs_procfixups: invalid offset: %x", fhp->fh_foff);
1807 		return (EINVAL);
1808 	}
1809 	fxp = (u_int16_t *) (buf + fhp->fh_foff);
1810 	cfxp = (u_int16_t *) (buf + ntmp->ntm_bps - 2);
1811 	fixup = *fxp++;
1812 	for (i = 1; i < fhp->fh_fnum; i++, fxp++) {
1813 		if (*cfxp != fixup) {
1814 			kprintf("ntfs_procfixups: fixup %d doesn't match\n", i);
1815 			return (EINVAL);
1816 		}
1817 		*cfxp = *fxp;
1818 		cfxp = (u_int16_t *)(((caddr_t) cfxp) + ntmp->ntm_bps);
1819 	}
1820 	return (0);
1821 }
1822 
1823 #if 0 /* UNUSED */
1824 int
1825 ntfs_runtocn(cn_t *cn,	struct ntfsmount *ntmp, u_int8_t *run, u_long len,
1826 	     cn_t vcn)
1827 {
1828 	cn_t            ccn = 0;
1829 	cn_t            ccl = 0;
1830 	u_long          off = 0;
1831 	int             error = 0;
1832 
1833 #if NTFS_DEBUG
1834 	int             i;
1835 	kprintf("ntfs_runtocn: run: 0x%p, %ld bytes, vcn:%ld\n",
1836 		run, len, (u_long) vcn);
1837 	kprintf("ntfs_runtocn: run: ");
1838 	for (i = 0; i < len; i++)
1839 		kprintf("0x%02x ", run[i]);
1840 	kprintf("\n");
1841 #endif
1842 
1843 	if (NULL == run) {
1844 		kprintf("ntfs_runtocn: run == NULL\n");
1845 		return (EINVAL);
1846 	}
1847 	do {
1848 		if (run[off] == 0) {
1849 			kprintf("ntfs_runtocn: vcn too big\n");
1850 			return (E2BIG);
1851 		}
1852 		vcn -= ccl;
1853 		error = ntfs_parserun(&ccn, &ccl, run, len, &off);
1854 		if (error) {
1855 			kprintf("ntfs_runtocn: ntfs_parserun failed\n");
1856 			return (error);
1857 		}
1858 	} while (ccl <= vcn);
1859 	*cn = ccn + vcn;
1860 	return (0);
1861 }
1862 #endif
1863 
1864 /*
1865  * this initializes toupper table & dependant variables to be ready for
1866  * later work
1867  */
1868 void
1869 ntfs_toupper_init(void)
1870 {
1871 	ntfs_toupper_tab = NULL;
1872 	lockinit(&ntfs_toupper_lock, "ntfs_toupper", 0, 0);
1873 	ntfs_toupper_usecount = 0;
1874 }
1875 
1876 /*
1877  * if the ntfs_toupper_tab[] is filled already, just raise use count;
1878  * otherwise read the data from the filesystem we are currently mounting
1879  */
1880 int
1881 ntfs_toupper_use(struct mount *mp, struct ntfsmount *ntmp)
1882 {
1883 	int error = 0;
1884 	struct vnode *vp;
1885 
1886 	/* get exclusive access */
1887 	LOCKMGR(&ntfs_toupper_lock, LK_EXCLUSIVE);
1888 
1889 	/* only read the translation data from a file if it hasn't been
1890 	 * read already */
1891 	if (ntfs_toupper_tab)
1892 		goto out;
1893 
1894 	/*
1895 	 * Read in Unicode lowercase -> uppercase translation file.
1896 	 * XXX for now, just the first 256 entries are used anyway,
1897 	 * so don't bother reading more
1898 	 */
1899 	ntfs_toupper_tab = kmalloc(65536 * sizeof(wchar), M_NTFSRDATA,
1900 				   M_WAITOK);
1901 
1902 	if ((error = VFS_VGET(mp, NULL, NTFS_UPCASEINO, &vp)))
1903 		goto out;
1904 	error = ntfs_readattr(ntmp, VTONT(vp), NTFS_A_DATA, NULL,
1905 			0, 65536*sizeof(wchar), (char *) ntfs_toupper_tab, NULL);
1906 	vput(vp);
1907 
1908     out:
1909 	ntfs_toupper_usecount++;
1910 	LOCKMGR(&ntfs_toupper_lock, LK_RELEASE);
1911 	return (error);
1912 }
1913 
1914 /*
1915  * lower the use count and if it reaches zero, free the memory
1916  * tied by toupper table
1917  */
1918 void
1919 ntfs_toupper_unuse(void)
1920 {
1921 	/* get exclusive access */
1922 	LOCKMGR(&ntfs_toupper_lock, LK_EXCLUSIVE);
1923 
1924 	ntfs_toupper_usecount--;
1925 	if (ntfs_toupper_usecount == 0) {
1926 		kfree(ntfs_toupper_tab, M_NTFSRDATA);
1927 		ntfs_toupper_tab = NULL;
1928 	}
1929 #ifdef DIAGNOSTIC
1930 	else if (ntfs_toupper_usecount < 0) {
1931 		panic("ntfs_toupper_unuse(): use count negative: %d",
1932 			ntfs_toupper_usecount);
1933 	}
1934 #endif
1935 
1936 	/* release the lock */
1937 	LOCKMGR(&ntfs_toupper_lock, LK_RELEASE);
1938 }
1939 
1940 int
1941 ntfs_u28_init(struct ntfsmount *ntmp, wchar *u2w, char *cs_local,
1942 	 char *cs_ntfs)
1943 {
1944 	char ** u28;
1945 	int i, j, h, l;
1946 
1947 	if (ntfs_iconv && cs_local) {
1948 		ntfs_iconv->open(cs_local, cs_ntfs, &ntmp->ntm_ic_u2l);
1949 		return (0);
1950 	}
1951 
1952 	u28 = kmalloc(256 * sizeof(char *), M_TEMP, M_WAITOK | M_ZERO);
1953 
1954 	for (i=0; i<256; i++) {
1955 		h = (u2w[i] >> 8) & 0xFF;
1956 		l = (u2w[i]) &0xFF;
1957 
1958 		if (u28[h] == NULL) {
1959 			u28[h] = kmalloc(256 * sizeof(char), M_TEMP, M_WAITOK);
1960 			for (j=0; j<256; j++)
1961 				u28[h][j] = '_';
1962 		}
1963 
1964 		u28[h][l] = i & 0xFF;
1965 	}
1966 
1967 	ntmp->ntm_u28 = u28;
1968 
1969 	return (0);
1970 }
1971 
1972 int
1973 ntfs_u28_uninit(struct ntfsmount *ntmp)
1974 {
1975 	char ** u28;
1976 	int i;
1977 
1978 	if (ntmp->ntm_u28 == NULL) {
1979 		if (ntfs_iconv && ntmp->ntm_ic_u2l) {
1980 			ntfs_iconv->close(ntmp->ntm_ic_u2l);
1981 		}
1982 		return (0);
1983 	}
1984 
1985 	if (ntmp->ntm_u28 == NULL)
1986 		return (0);
1987 
1988 	u28 = ntmp->ntm_u28;
1989 
1990 	for (i=0; i<256; i++)
1991 		if (u28[i] != NULL)
1992 			kfree(u28[i], M_TEMP);
1993 
1994 	kfree(u28, M_TEMP);
1995 
1996 	return (0);
1997 }
1998 
1999 int
2000 ntfs_82u_init(struct ntfsmount *ntmp, char *cs_local, char *cs_ntfs)
2001 
2002 {
2003 	wchar * _82u;
2004 	int i;
2005 
2006 	if (ntfs_iconv && cs_local) {
2007 		ntfs_iconv->open(cs_ntfs, cs_local, &ntmp->ntm_ic_l2u);
2008 		return (0);
2009 	}
2010 
2011 	_82u = kmalloc(256 * sizeof(wchar), M_TEMP, M_WAITOK);
2012 
2013 	for (i=0; i<256; i++)
2014 		_82u[i] = i;
2015 
2016 	ntmp->ntm_82u = _82u;
2017 
2018 	return (0);
2019 }
2020 
2021 int
2022 ntfs_82u_uninit(struct ntfsmount *ntmp)
2023 {
2024 	if (ntmp->ntm_82u == NULL) {
2025 		if (ntfs_iconv && ntmp->ntm_ic_l2u) {
2026 			ntfs_iconv->close(ntmp->ntm_ic_l2u);
2027 		}
2028 		return (0);
2029 	}
2030 
2031 	kfree(ntmp->ntm_82u, M_TEMP);
2032 	return (0);
2033 }
2034 
2035 /*
2036  * maps the Unicode char to 8bit equivalent
2037  * XXX currently only gets lower 8bit from the Unicode char
2038  * and substitutes a '_' for it if the result would be '\0';
2039  * something better has to be definitely though out
2040  */
2041 wchar
2042 ntfs_u28(struct ntfsmount *ntmp, wchar wc)
2043 {
2044 	char *p, *outp, inbuf[3], outbuf[3];
2045 	size_t ilen, olen;
2046 
2047 	if (ntfs_iconv && ntmp->ntm_ic_u2l) {
2048 		ilen = olen = 2;
2049 		inbuf[0] = (char)(wc>>8);
2050 		inbuf[1] = (char)wc;
2051 		inbuf[2] = '\0';
2052 		p = inbuf;
2053 		outp = outbuf;
2054 		ntfs_iconv->convchr(ntmp->ntm_ic_u2l,
2055 		    (const char **)(void *)&p, &ilen, &outp, &olen);
2056 		if (olen == 1) {
2057 			return ((wchar)(outbuf[0]&0xFF));
2058 		} else if (olen == 0) {
2059 			return ((wchar)((outbuf[0]<<8) | (outbuf[1]&0xFF)));
2060 		}
2061 		return ('?');
2062 	}
2063 
2064 	p = ntmp->ntm_u28[(wc>>8)&0xFF];
2065 	if (p == NULL)
2066 		return ('_');
2067 	return (p[wc&0xFF]);
2068 }
2069 
2070 wchar
2071 ntfs_82u(struct ntfsmount *ntmp,
2072 	wchar wc,
2073 	int *len)
2074 {
2075 	char *p, *outp, inbuf[3], outbuf[3];
2076 	wchar uc;
2077 	size_t ilen, olen;
2078 
2079 	if (ntfs_iconv && ntmp->ntm_ic_l2u) {
2080 		ilen = (size_t)*len;
2081 		olen = 2;
2082 
2083 		inbuf[0] = (char)(wc>>8);
2084 		inbuf[1] = (char)wc;
2085 		inbuf[2] = '\0';
2086 		p = inbuf;
2087 		outp = outbuf;
2088 		ntfs_iconv->convchr(ntmp->ntm_ic_l2u,
2089 		    (const char **)(void *)&p, &ilen, &outp, &olen);
2090 		*len -= (int)ilen;
2091 		uc = (wchar)((outbuf[0]<<8) | (outbuf[1]&0xFF));
2092 
2093 		return (uc);
2094 	}
2095 
2096 	if (ntmp->ntm_82u != NULL)
2097 		return (ntmp->ntm_82u[wc&0xFF]);
2098 
2099 	return ('?');
2100 }
2101