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