(* libguestfs * Copyright (C) 2009-2011 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (* Please read generator/README first. *) open Printf open Generator_types open Generator_utils open Generator_pr open Generator_docstrings open Generator_optgroups open Generator_actions open Generator_structs open Generator_c (* Generate Java bindings GuestFS.java file. *) let rec generate_java_java () = generate_header CStyle LGPLv2plus; pr "\ package com.redhat.et.libguestfs; import java.util.HashMap; import java.util.Map; import com.redhat.et.libguestfs.LibGuestFSException; import com.redhat.et.libguestfs.PV; import com.redhat.et.libguestfs.VG; import com.redhat.et.libguestfs.LV; import com.redhat.et.libguestfs.Stat; import com.redhat.et.libguestfs.StatVFS; import com.redhat.et.libguestfs.IntBool; import com.redhat.et.libguestfs.Dirent; /** * The GuestFS object is a libguestfs handle. * * @author rjones */ public class GuestFS { // Load the native code. static { System.loadLibrary (\"guestfs_jni\"); } /** * The native guestfs_h pointer. */ long g; /** * Create a libguestfs handle. * * @throws LibGuestFSException */ public GuestFS () throws LibGuestFSException { g = _create (); } private native long _create () throws LibGuestFSException; /** * Close a libguestfs handle. * * You can also leave handles to be collected by the garbage * collector, but this method ensures that the resources used * by the handle are freed up immediately. If you call any * other methods after closing the handle, you will get an * exception. * * @throws LibGuestFSException */ public void close () throws LibGuestFSException { if (g != 0) _close (g); g = 0; } private native void _close (long g) throws LibGuestFSException; public void finalize () throws LibGuestFSException { close (); } "; List.iter ( fun (name, (ret, args, optargs as style), _, flags, _, shortdesc, longdesc) -> if not (List.mem NotInDocs flags); then ( let doc = replace_str longdesc "C [] then doc ^ "\n\nOptional arguments are supplied in the final Map parameter, which is a hash of the argument name to its value (cast to Object). Pass an empty Map or null for no optional arguments." else doc in let doc = if List.mem ProtocolLimitWarning flags then doc ^ "\n\n" ^ protocol_limit_warning else doc in let doc = if List.mem DangerWillRobinson flags then doc ^ "\n\n" ^ danger_will_robinson else doc in let doc = match deprecation_notice flags with | None -> doc | Some txt -> doc ^ "\n\n" ^ txt in let doc = pod2text ~width:60 name doc in let doc = List.map ( (* RHBZ#501883 *) function | "" -> "

" | nonempty -> nonempty ) doc in let doc = String.concat "\n * " doc in pr " /**\n"; pr " * %s\n" shortdesc; pr " *

\n"; pr " * %s\n" doc; pr " * @throws LibGuestFSException\n"; pr " */\n"; ); pr " "; generate_java_prototype ~public:true ~semicolon:false name style; pr "\n"; pr " {\n"; pr " if (g == 0)\n"; pr " throw new LibGuestFSException (\"%s: handle is closed\");\n" name; if optargs <> [] then ( pr "\n"; pr " /* Unpack optional args. */\n"; pr " Object _optobj;\n"; pr " long _optargs_bitmask = 0;\n"; iteri ( fun i argt -> let t, boxed_t, convert, n, default = match argt with | Bool n -> "boolean", "Boolean", ".booleanValue()", n, "false" | Int n -> "int", "Integer", ".intValue()", n, "0" | Int64 n -> "long", "Long", ".longValue()", n, "0" | String n -> "String", "String", "", n, "\"\"" | _ -> assert false in pr " %s %s = %s;\n" t n default; pr " _optobj = null;\n"; pr " if (optargs != null)\n"; pr " _optobj = optargs.get (\"%s\");\n" n; pr " if (_optobj != null) {\n"; pr " %s = ((%s) _optobj)%s;\n" n boxed_t convert; pr " _optargs_bitmask |= %Ld;\n" (Int64.shift_left Int64.one i); pr " }\n"; ) optargs ); pr "\n"; (match ret with | RErr -> pr " _%s " name; generate_java_call_args ~handle:"g" style; pr ";\n" | RHashtable _ -> pr " String[] r = _%s " name; generate_java_call_args ~handle:"g" style; pr ";\n"; pr "\n"; pr " HashMap rhash = new HashMap ();\n"; pr " for (int i = 0; i < r.length; i += 2)\n"; pr " rhash.put (r[i], r[i+1]);\n"; pr " return rhash;\n" | _ -> pr " return _%s " name; generate_java_call_args ~handle:"g" style; pr ";\n" ); pr " }\n"; pr "\n"; pr " "; generate_java_prototype ~privat:true ~native:true name style; pr "\n"; pr "\n"; ) all_functions; pr "}\n" (* Generate Java call arguments, eg "(handle, foo, bar)" *) and generate_java_call_args ~handle (_, args, optargs) = pr "(%s" handle; List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args; if optargs <> [] then ( pr ", _optargs_bitmask"; List.iter (fun arg -> pr ", %s" (name_of_argt arg)) optargs ); pr ")" and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false) ?(semicolon=true) name (ret, args, optargs) = if privat then pr "private "; if public then pr "public "; if native then pr "native "; (* return type *) (match ret with | RErr -> pr "void "; | RInt _ -> pr "int "; | RInt64 _ -> pr "long "; | RBool _ -> pr "boolean "; | RConstString _ | RConstOptString _ | RString _ | RBufferOut _ -> pr "String "; | RStringList _ -> pr "String[] "; | RStruct (_, typ) -> let name = java_name_of_struct typ in pr "%s " name; | RStructList (_, typ) -> let name = java_name_of_struct typ in pr "%s[] " name; | RHashtable _ -> if not native then pr "Map " else pr "String[] "; ); if native then pr "_%s " name else pr "%s " name; pr "("; let needs_comma = ref false in if native then ( pr "long g"; needs_comma := true ); (* args *) List.iter ( fun arg -> if !needs_comma then pr ", "; needs_comma := true; match arg with | Pathname n | Device n | Dev_or_Path n | String n | OptString n | FileIn n | FileOut n | Key n -> pr "String %s" n | BufferIn n -> pr "byte[] %s" n | StringList n | DeviceList n -> pr "String[] %s" n | Bool n -> pr "boolean %s" n | Int n -> pr "int %s" n | Int64 n | Pointer (_, n) -> pr "long %s" n ) args; if optargs <> [] then ( if !needs_comma then pr ", "; needs_comma := true; if not native then pr "Map optargs" else ( pr "long _optargs_bitmask"; List.iter ( fun argt -> match argt with | Bool n -> pr ", boolean %s" n | Int n -> pr ", int %s" n | Int64 n -> pr ", long %s" n | String n -> pr ", String %s" n | _ -> assert false ) optargs ) ); pr ")\n"; pr " throws LibGuestFSException"; if semicolon then pr ";" and generate_java_struct jtyp cols () = generate_header CStyle LGPLv2plus; pr "\ package com.redhat.et.libguestfs; /** * Libguestfs %s structure. * * @author rjones * @see GuestFS */ public class %s { " jtyp jtyp; List.iter ( function | name, FString | name, FUUID | name, FBuffer -> pr " public String %s;\n" name | name, (FBytes|FUInt64|FInt64) -> pr " public long %s;\n" name | name, (FUInt32|FInt32) -> pr " public int %s;\n" name | name, FChar -> pr " public char %s;\n" name | name, FOptPercent -> pr " /* The next field is [0..100] or -1 meaning 'not present': */\n"; pr " public float %s;\n" name ) cols; pr "}\n" and generate_java_c () = generate_header CStyle LGPLv2plus; pr "\ #include #include #include #include \"com_redhat_et_libguestfs_GuestFS.h\" #include \"guestfs.h\" /* Note that this function returns. The exception is not thrown * until after the wrapper function returns. */ static void throw_exception (JNIEnv *env, const char *msg) { jclass cl; cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/LibGuestFSException\"); (*env)->ThrowNew (env, cl, msg); } JNIEXPORT jlong JNICALL Java_com_redhat_et_libguestfs_GuestFS__1create (JNIEnv *env, jobject obj) { guestfs_h *g; g = guestfs_create (); if (g == NULL) { throw_exception (env, \"GuestFS.create: failed to allocate handle\"); return 0; } guestfs_set_error_handler (g, NULL, NULL); return (jlong) (long) g; } JNIEXPORT void JNICALL Java_com_redhat_et_libguestfs_GuestFS__1close (JNIEnv *env, jobject obj, jlong jg) { guestfs_h *g = (guestfs_h *) (long) jg; guestfs_close (g); } "; List.iter ( fun (name, (ret, args, optargs as style), _, _, _, _, _) -> pr "JNIEXPORT "; (match ret with | RErr -> pr "void "; | RInt _ -> pr "jint "; | RInt64 _ -> pr "jlong "; | RBool _ -> pr "jboolean "; | RConstString _ | RConstOptString _ | RString _ | RBufferOut _ -> pr "jstring "; | RStruct _ | RHashtable _ -> pr "jobject "; | RStringList _ | RStructList _ -> pr "jobjectArray "; ); pr "JNICALL\n"; pr "Java_com_redhat_et_libguestfs_GuestFS_"; pr "%s" (replace_str ("_" ^ name) "_" "_1"); pr " (JNIEnv *env, jobject obj, jlong jg"; List.iter ( function | Pathname n | Device n | Dev_or_Path n | String n | OptString n | FileIn n | FileOut n | Key n -> pr ", jstring j%s" n | BufferIn n -> pr ", jbyteArray j%s" n | StringList n | DeviceList n -> pr ", jobjectArray j%s" n | Bool n -> pr ", jboolean j%s" n | Int n -> pr ", jint j%s" n | Int64 n | Pointer (_, n) -> pr ", jlong j%s" n ) args; if optargs <> [] then ( pr ", jlong joptargs_bitmask"; List.iter ( function | Bool n -> pr ", jboolean j%s" n | Int n -> pr ", jint j%s" n | Int64 n -> pr ", jlong j%s" n | String n -> pr ", jstring j%s" n | _ -> assert false ) optargs ); pr ")\n"; pr "{\n"; pr " guestfs_h *g = (guestfs_h *) (long) jg;\n"; (match ret with | RErr -> pr " int r;\n" | RBool _ | RInt _ -> pr " int r;\n" | RInt64 _ -> pr " int64_t r;\n" | RConstString _ -> pr " const char *r;\n" | RConstOptString _ -> pr " const char *r;\n" | RString _ -> pr " jstring jr;\n"; pr " char *r;\n" | RStringList _ | RHashtable _ -> pr " jobjectArray jr;\n"; pr " size_t r_len;\n"; pr " jclass cl;\n"; pr " jstring jstr;\n"; pr " char **r;\n" | RStruct (_, typ) -> pr " jobject jr;\n"; pr " jclass cl;\n"; pr " jfieldID fl;\n"; pr " struct guestfs_%s *r;\n" typ | RStructList (_, typ) -> pr " jobjectArray jr;\n"; pr " jclass cl;\n"; pr " jfieldID fl;\n"; pr " jobject jfl;\n"; pr " struct guestfs_%s_list *r;\n" typ | RBufferOut _ -> pr " jstring jr;\n"; pr " char *r;\n"; pr " size_t size;\n" ); List.iter ( function | Pathname n | Device n | Dev_or_Path n | String n | OptString n | FileIn n | FileOut n | Key n -> pr " const char *%s;\n" n | BufferIn n -> pr " char *%s;\n" n; pr " size_t %s_size;\n" n | StringList n | DeviceList n -> pr " size_t %s_len;\n" n; pr " char **%s;\n" n | Bool n | Int n -> pr " int %s;\n" n | Int64 n -> pr " int64_t %s;\n" n | Pointer (t, n) -> pr " %s %s;\n" t n ) args; if optargs <> [] then ( pr " struct guestfs_%s_argv optargs_s;\n" name; pr " const struct guestfs_%s_argv *optargs = &optargs_s;\n" name ); let needs_i = (match ret with | RStringList _ | RStructList _ | RHashtable _ -> true | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _ | RConstOptString _ | RString _ | RBufferOut _ | RStruct _ -> false) || List.exists (function | StringList _ -> true | DeviceList _ -> true | _ -> false) args in if needs_i then pr " size_t i;\n"; pr "\n"; (* Get the parameters. *) List.iter ( function | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n | Key n -> pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n | OptString n -> (* This is completely undocumented, but Java null becomes * a NULL parameter. *) pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n | BufferIn n -> pr " %s = (char *) (*env)->GetByteArrayElements (env, j%s, NULL);\n" n n; pr " %s_size = (*env)->GetArrayLength (env, j%s);\n" n n | StringList n | DeviceList n -> pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n; pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n; pr " for (i = 0; i < %s_len; ++i) {\n" n; pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n" n; pr " %s[i] = (char *) (*env)->GetStringUTFChars (env, o, NULL);\n" n; pr " }\n"; pr " %s[%s_len] = NULL;\n" n n; | Bool n | Int n | Int64 n -> pr " %s = j%s;\n" n n | Pointer (t, n) -> pr " %s = (%s) j%s;\n" n t n ) args; if optargs <> [] then ( pr " optargs_s.bitmask = joptargs_bitmask;\n"; List.iter ( function | Bool n | Int n | Int64 n -> pr " optargs_s.%s = j%s;\n" n n | String n -> pr " optargs_s.%s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n | _ -> assert false ) optargs; ); pr "\n"; (* Make the call. *) if optargs = [] then pr " r = guestfs_%s " name else pr " r = guestfs_%s_argv " name; generate_c_call_args ~handle:"g" style; pr ";\n"; pr "\n"; (* Release the parameters. *) List.iter ( function | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n | Key n -> pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n | OptString n -> pr " if (j%s)\n" n; pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n | BufferIn n -> pr " (*env)->ReleaseByteArrayElements (env, j%s, (jbyte *) %s, 0);\n" n n | StringList n | DeviceList n -> pr " for (i = 0; i < %s_len; ++i) {\n" n; pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n" n; pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n; pr " }\n"; pr " free (%s);\n" n | Bool _ | Int _ | Int64 _ | Pointer _ -> () ) args; List.iter ( function | Bool n | Int n | Int64 n -> () | String n -> pr " (*env)->ReleaseStringUTFChars (env, j%s, optargs_s.%s);\n" n n | _ -> assert false ) optargs; pr "\n"; (* Check for errors. *) (match errcode_of_ret ret with | `CannotReturnError -> () | (`ErrorIsMinusOne|`ErrorIsNULL) as errcode -> (match errcode with | `ErrorIsMinusOne -> pr " if (r == -1) {\n"; | `ErrorIsNULL -> pr " if (r == NULL) {\n"; ); pr " throw_exception (env, guestfs_last_error (g));\n"; (match ret with | RErr -> pr " return;\n" | RInt _ | RInt64 _ | RBool _ -> pr " return -1;\n" | RConstString _ | RConstOptString _ | RString _ | RBufferOut _ | RStruct _ | RHashtable _ | RStringList _ | RStructList _ -> pr " return NULL;\n" ); pr " }\n" ); (* Return value. *) (match ret with | RErr -> () | RInt _ -> pr " return (jint) r;\n" | RBool _ -> pr " return (jboolean) r;\n" | RInt64 _ -> pr " return (jlong) r;\n" | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n" | RConstOptString _ -> pr " return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n" | RString _ -> pr " jr = (*env)->NewStringUTF (env, r);\n"; pr " free (r);\n"; pr " return jr;\n" | RStringList _ | RHashtable _ -> pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n"; pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n"; pr " jstr = (*env)->NewStringUTF (env, \"\");\n"; pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n"; pr " for (i = 0; i < r_len; ++i) {\n"; pr " jstr = (*env)->NewStringUTF (env, r[i]);\n"; pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n"; pr " free (r[i]);\n"; pr " }\n"; pr " free (r);\n"; pr " return jr;\n" | RStruct (_, typ) -> let jtyp = java_name_of_struct typ in let cols = cols_of_struct typ in generate_java_struct_return typ jtyp cols | RStructList (_, typ) -> let jtyp = java_name_of_struct typ in let cols = cols_of_struct typ in generate_java_struct_list_return typ jtyp cols | RBufferOut _ -> pr " jr = (*env)->NewStringUTF (env, r); // XXX size\n"; pr " free (r);\n"; pr " return jr;\n" ); pr "}\n"; pr "\n" ) all_functions and generate_java_struct_return typ jtyp cols = pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp; pr " jr = (*env)->AllocObject (env, cl);\n"; List.iter ( function | name, FString -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name; pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name; | name, FUUID -> pr " {\n"; pr " char s[33];\n"; pr " memcpy (s, r->%s, 32);\n" name; pr " s[32] = 0;\n"; pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name; pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n"; pr " }\n"; | name, FBuffer -> pr " {\n"; pr " int len = r->%s_len;\n" name; pr " char s[len+1];\n"; pr " memcpy (s, r->%s, len);\n" name; pr " s[len] = 0;\n"; pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name; pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n"; pr " }\n"; | name, (FBytes|FUInt64|FInt64) -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name; pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name; | name, (FUInt32|FInt32) -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name; pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name; | name, FOptPercent -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name; pr " (*env)->SetFloatField (env, jr, fl, r->%s);\n" name; | name, FChar -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name; pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name; ) cols; pr " free (r);\n"; pr " return jr;\n" and generate_java_struct_list_return typ jtyp cols = pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp; pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n"; pr " for (i = 0; i < r->len; ++i) {\n"; pr " jfl = (*env)->AllocObject (env, cl);\n"; List.iter ( function | name, FString -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name; pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name; | name, FUUID -> pr " {\n"; pr " char s[33];\n"; pr " memcpy (s, r->val[i].%s, 32);\n" name; pr " s[32] = 0;\n"; pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name; pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n"; pr " }\n"; | name, FBuffer -> pr " {\n"; pr " int len = r->val[i].%s_len;\n" name; pr " char s[len+1];\n"; pr " memcpy (s, r->val[i].%s, len);\n" name; pr " s[len] = 0;\n"; pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name; pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n"; pr " }\n"; | name, (FBytes|FUInt64|FInt64) -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name; pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name; | name, (FUInt32|FInt32) -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name; pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name; | name, FOptPercent -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name; pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name; | name, FChar -> pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name; pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name; ) cols; pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n"; pr " }\n"; pr " guestfs_free_%s_list (r);\n" typ; pr " return jr;\n" and generate_java_makefile_inc () = generate_header HashStyle GPLv2plus; pr "java_built_sources = \\\n"; List.iter ( fun (typ, jtyp) -> pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp; ) java_structs; pr "\tcom/redhat/et/libguestfs/GuestFS.java\n" '>600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

/*
 *    seagate.c Copyright (C) 1992, 1993 Drew Eckhardt
 *      low level scsi driver for ST01/ST02, Future Domain TMC-885,
 *      TMC-950 by Drew Eckhardt <drew@colorado.edu>
 *
 *      Note : TMC-880 boards don't work because they have two bits in
 *              the status register flipped, I'll fix this "RSN"
 *	[why do I have strong feeling that above message is from 1993? :-)
 *	        pavel@ucw.cz]
 *
 *      This card does all the I/O via memory mapped I/O, so there is no need
 *      to check or allocate a region of the I/O address space.
 */

/* 1996 - to use new read{b,w,l}, write{b,w,l}, and phys_to_virt
 * macros, replaced assembler routines with C. There's probably a
 * performance hit, but I only have a cdrom and can't tell. Define
 * SEAGATE_USE_ASM if you want the old assembler code -- SJT
 *
 * 1998-jul-29 - created DPRINTK macros and made it work under 
 * linux 2.1.112, simplified some #defines etc. <pavel@ucw.cz>
 *
 * Aug 2000 - aeb - deleted seagate_st0x_biosparam(). It would try to
 * read the physical disk geometry, a bad mistake. Of course it doesn't
 * matter much what geometry one invents, but on large disks it
 * returned 256 (or more) heads, causing all kind of failures.
 * Of course this means that people might see a different geometry now,
 * so boot parameters may be necessary in some cases.
 */

/*
 * Configuration :
 * To use without BIOS -DOVERRIDE=base_address -DCONTROLLER=FD or SEAGATE
 * -DIRQ will override the default of 5.
 * Note: You can now set these options from the kernel's "command line".
 * The syntax is:
 *
 *     st0x=ADDRESS,IRQ                (for a Seagate controller)
 * or:
 *     tmc8xx=ADDRESS,IRQ              (for a TMC-8xx or TMC-950 controller)
 * eg:
 *     tmc8xx=0xC8000,15
 *
 * will configure the driver for a TMC-8xx style controller using IRQ 15
 * with a base address of 0xC8000.
 *
 * -DARBITRATE 
 *      Will cause the host adapter to arbitrate for the
 *      bus for better SCSI-II compatibility, rather than just
 *      waiting for BUS FREE and then doing its thing.  Should
 *      let us do one command per Lun when I integrate my
 *      reorganization changes into the distribution sources.
 *
 * -DDEBUG=65535
 *      Will activate debug code.
 *
 * -DFAST or -DFAST32 
 *      Will use blind transfers where possible
 *
 * -DPARITY  
 *      This will enable parity.
 *
 * -DSEAGATE_USE_ASM
 *      Will use older seagate assembly code. should be (very small amount)
 *      Faster.
 *
 * -DSLOW_RATE=50
 *      Will allow compatibility with broken devices that don't
 *      handshake fast enough (ie, some CD ROM's) for the Seagate
 *      code.
 *
 *      50 is some number, It will let you specify a default
 *      transfer rate if handshaking isn't working correctly.
 *
 * -DOLDCNTDATASCEME  There is a new sceme to set the CONTROL
 *                    and DATA reigsters which complies more closely
 *                    with the SCSI2 standard. This hopefully eliminates
 *                    the need to swap the order these registers are
 *                    'messed' with. It makes the following two options
 *                    obsolete. To reenable the old sceme define this.
 *
 * The following to options are patches from the SCSI.HOWTO
 *
 * -DSWAPSTAT  This will swap the definitions for STAT_MSG and STAT_CD.
 *
 * -DSWAPCNTDATA  This will swap the order that seagate.c messes with
 *                the CONTROL an DATA registers.
 */

#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/signal.h>
#include <linux/string.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/blkdev.h>
#include <linux/stat.h>
#include <linux/delay.h>

#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>

#include "scsi.h"
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_host.h>
#include "seagate.h"

#include <scsi/scsi_ioctl.h>

#ifdef DEBUG
#define DPRINTK( when, msg... ) do { if ( (DEBUG & (when)) == (when) ) printk( msg ); } while (0)
#else
#define DPRINTK( when, msg... ) do { } while (0)
#endif
#define DANY( msg... ) DPRINTK( 0xffff, msg );

#ifndef IRQ
#define IRQ 5
#endif

#ifdef FAST32
#define FAST
#endif

#undef LINKED			/* Linked commands are currently broken! */

#if defined(OVERRIDE) && !defined(CONTROLLER)
#error Please use -DCONTROLLER=SEAGATE or -DCONTROLLER=FD to override controller type
#endif

#ifndef __i386__
#undef SEAGATE_USE_ASM
#endif

/*
	Thanks to Brian Antoine for the example code in his Messy-Loss ST-01
		driver, and Mitsugu Suzuki for information on the ST-01
		SCSI host.
*/

/*
	CONTROL defines
*/

#define CMD_RST 		0x01
#define CMD_SEL 		0x02
#define CMD_BSY 		0x04
#define CMD_ATTN    		0x08
#define CMD_START_ARB		0x10
#define CMD_EN_PARITY		0x20
#define CMD_INTR		0x40
#define CMD_DRVR_ENABLE		0x80

/*
	STATUS
*/
#ifdef SWAPSTAT
#define STAT_MSG		0x08
#define STAT_CD			0x02
#else
#define STAT_MSG		0x02
#define STAT_CD			0x08
#endif

#define STAT_BSY		0x01
#define STAT_IO			0x04
#define STAT_REQ		0x10
#define STAT_SEL		0x20
#define STAT_PARITY		0x40
#define STAT_ARB_CMPL		0x80

/* 
	REQUESTS
*/

#define REQ_MASK (STAT_CD |  STAT_IO | STAT_MSG)
#define REQ_DATAOUT 0
#define REQ_DATAIN STAT_IO
#define REQ_CMDOUT STAT_CD
#define REQ_STATIN (STAT_CD | STAT_IO)
#define REQ_MSGOUT (STAT_MSG | STAT_CD)
#define REQ_MSGIN (STAT_MSG | STAT_CD | STAT_IO)

extern volatile int seagate_st0x_timeout;

#ifdef PARITY
#define BASE_CMD CMD_EN_PARITY
#else
#define BASE_CMD  0
#endif

/*
	Debugging code
*/

#define PHASE_BUS_FREE 1
#define PHASE_ARBITRATION 2
#define PHASE_SELECTION 4
#define PHASE_DATAIN 8
#define PHASE_DATAOUT 0x10
#define PHASE_CMDOUT 0x20
#define PHASE_MSGIN 0x40
#define PHASE_MSGOUT 0x80
#define PHASE_STATUSIN 0x100
#define PHASE_ETC (PHASE_DATAIN | PHASE_DATAOUT | PHASE_CMDOUT | PHASE_MSGIN | PHASE_MSGOUT | PHASE_STATUSIN)
#define PRINT_COMMAND 0x200
#define PHASE_EXIT 0x400
#define PHASE_RESELECT 0x800
#define DEBUG_FAST 0x1000
#define DEBUG_SG   0x2000
#define DEBUG_LINKED	0x4000
#define DEBUG_BORKEN	0x8000

/* 
 *	Control options - these are timeouts specified in .01 seconds.
 */

/* 30, 20 work */
#define ST0X_BUS_FREE_DELAY 25
#define ST0X_SELECTION_DELAY 25

#define SEAGATE 1		/* these determine the type of the controller */
#define FD	2

#define ST0X_ID_STR	"Seagate ST-01/ST-02"
#define FD_ID_STR	"TMC-8XX/TMC-950"

static int internal_command (unsigned char target, unsigned char lun,
			     const void *cmnd,
			     void *buff, int bufflen, int reselect);

static int incommand;		/* set if arbitration has finished
				   and we are in some command phase. */

static unsigned int base_address = 0;	/* Where the card ROM starts, used to 
					   calculate memory mapped register
					   location.  */

static void __iomem *st0x_cr_sr;	/* control register write, status
					   register read.  256 bytes in
					   length.
					   Read is status of SCSI BUS, as per 
					   STAT masks.  */

static void __iomem *st0x_dr;	/* data register, read write 256
				   bytes in length.  */

static volatile int st0x_aborted = 0;	/* set when we are aborted, ie by a
					   time out, etc.  */

static unsigned char controller_type = 0;	/* set to SEAGATE for ST0x
						   boards or FD for TMC-8xx
						   boards */
static int irq = IRQ;

module_param(base_address, uint, 0);
module_param(controller_type, byte, 0);
module_param(irq, int, 0);
MODULE_LICENSE("GPL");


#define retcode(result) (((result) << 16) | (message << 8) | status)
#define STATUS ((u8) readb(st0x_cr_sr))
#define DATA ((u8) readb(st0x_dr))
#define WRITE_CONTROL(d) { writeb((d), st0x_cr_sr); }
#define WRITE_DATA(d) { writeb((d), st0x_dr); }

#ifndef OVERRIDE
static unsigned int seagate_bases[] = {
	0xc8000, 0xca000, 0xcc000,
	0xce000, 0xdc000, 0xde000
};

typedef struct {
	const unsigned char *signature;
	unsigned offset;
	unsigned length;
	unsigned char type;
} Signature;

static Signature __initdata signatures[] = {
	{"ST01 v1.7  (C) Copyright 1987 Seagate", 15, 37, SEAGATE},
	{"SCSI BIOS 2.00  (C) Copyright 1987 Seagate", 15, 40, SEAGATE},

/*
 * The following two lines are NOT mistakes.  One detects ROM revision
 * 3.0.0, the other 3.2.  Since seagate has only one type of SCSI adapter,
 * and this is not going to change, the "SEAGATE" and "SCSI" together
 * are probably "good enough"
 */

	{"SEAGATE SCSI BIOS ", 16, 17, SEAGATE},
	{"SEAGATE SCSI BIOS ", 17, 17, SEAGATE},

/*
 * However, future domain makes several incompatible SCSI boards, so specific
 * signatures must be used.
 */

	{"FUTURE DOMAIN CORP. (C) 1986-1989 V5.0C2/14/89", 5, 46, FD},
	{"FUTURE DOMAIN CORP. (C) 1986-1989 V6.0A7/28/89", 5, 46, FD},
	{"FUTURE DOMAIN CORP. (C) 1986-1990 V6.0105/31/90", 5, 47, FD},
	{"FUTURE DOMAIN CORP. (C) 1986-1990 V6.0209/18/90", 5, 47, FD},
	{"FUTURE DOMAIN CORP. (C) 1986-1990 V7.009/18/90", 5, 46, FD},
	{"FUTURE DOMAIN CORP. (C) 1992 V8.00.004/02/92", 5, 44, FD},
	{"IBM F1 BIOS V1.1004/30/92", 5, 25, FD},
	{"FUTURE DOMAIN TMC-950", 5, 21, FD},
	/* Added for 2.2.16 by Matthias_Heidbrink@b.maus.de */
	{"IBM F1 V1.2009/22/93", 5, 25, FD},
};

#define NUM_SIGNATURES (sizeof(signatures) / sizeof(Signature))
#endif				/* n OVERRIDE */

/*
 * hostno stores the hostnumber, as told to us by the init routine.
 */

static int hostno = -1;
static void seagate_reconnect_intr (int, void *, struct pt_regs *);
static irqreturn_t do_seagate_reconnect_intr (int, void *, struct pt_regs *);

#ifdef FAST
static int fast = 1;
#else
#define fast 0
#endif

#ifdef SLOW_RATE
/*
 * Support for broken devices :
 * The Seagate board has a handshaking problem.  Namely, a lack
 * thereof for slow devices.  You can blast 600K/second through
 * it if you are polling for each byte, more if you do a blind
 * transfer.  In the first case, with a fast device, REQ will
 * transition high-low or high-low-high before your loop restarts
 * and you'll have no problems.  In the second case, the board
 * will insert wait states for up to 13.2 usecs for REQ to
 * transition low->high, and everything will work.
 *
 * However, there's nothing in the state machine that says
 * you *HAVE* to see a high-low-high set of transitions before
 * sending the next byte, and slow things like the Trantor CD ROMS
 * will break because of this.
 *
 * So, we need to slow things down, which isn't as simple as it
 * seems.  We can't slow things down period, because then people
 * who don't recompile their kernels will shoot me for ruining
 * their performance.  We need to do it on a case per case basis.
 *
 * The best for performance will be to, only for borken devices
 * (this is stored on a per-target basis in the scsi_devices array)
 *
 * Wait for a low->high transition before continuing with that
 * transfer.  If we timeout, continue anyways.  We don't need
 * a long timeout, because REQ should only be asserted until the
 * corresponding ACK is received and processed.
 *
 * Note that we can't use the system timer for this, because of
 * resolution, and we *really* can't use the timer chip since
 * gettimeofday() and the beeper routines use that.  So,
 * the best thing for us to do will be to calibrate a timing
 * loop in the initialization code using the timer chip before
 * gettimeofday() can screw with it.
 *
 * FIXME: this is broken (not borken :-). Empty loop costs less than
 * loop with ISA access in it! -- pavel@ucw.cz
 */

static int borken_calibration = 0;

static void __init borken_init (void)
{
	register int count = 0, start = jiffies + 1, stop = start + 25;

	/* FIXME: There may be a better approach, this is a straight port for
	   now */
	preempt_disable();
	while (time_before (jiffies, start))
		cpu_relax();
	for (; time_before (jiffies, stop); ++count)
		cpu_relax();
	preempt_enable();

/*
 * Ok, we now have a count for .25 seconds.  Convert to a
 * count per second and divide by transfer rate in K.  */

	borken_calibration = (count * 4) / (SLOW_RATE * 1024);

	if (borken_calibration < 1)
		borken_calibration = 1;
}

static inline void borken_wait (void)
{
	register int count;

	for (count = borken_calibration; count && (STATUS & STAT_REQ); --count)
		cpu_relax();
	     	
#if (DEBUG & DEBUG_BORKEN)
	if (count)
		printk ("scsi%d : borken timeout\n", hostno);
#endif
}

#endif				/* def SLOW_RATE */

/* These beasts only live on ISA, and ISA means 8MHz. Each ULOOP()
 * contains at least one ISA access, which takes more than 0.125
 * usec. So if we loop 8 times time in usec, we are safe.
 */

#define ULOOP( i ) for (clock = i*8;;)
#define TIMEOUT (!(clock--))

int __init seagate_st0x_detect (Scsi_Host_Template * tpnt)
{
	struct Scsi_Host *instance;
	int i, j;
	unsigned long cr, dr;

	tpnt->proc_name = "seagate";
/*
 *	First, we try for the manual override.
 */
	DANY ("Autodetecting ST0x / TMC-8xx\n");

	if (hostno != -1) {
		printk (KERN_ERR "seagate_st0x_detect() called twice?!\n");
		return 0;
	}

/* If the user specified the controller type from the command line,
   controller_type will be non-zero, so don't try to detect one */

	if (!controller_type) {
#ifdef OVERRIDE
		base_address = OVERRIDE;
		controller_type = CONTROLLER;

		DANY ("Base address overridden to %x, controller type is %s\n",
		      base_address,
		      controller_type == SEAGATE ? "SEAGATE" : "FD");
#else				/* OVERRIDE */
/*
 * 	To detect this card, we simply look for the signature
 *      from the BIOS version notice in all the possible locations
 *      of the ROM's.  This has a nice side effect of not trashing
 *      any register locations that might be used by something else.
 *
 * XXX - note that we probably should be probing the address
 * space for the on-board RAM instead.
 */

		for (i = 0; i < (sizeof (seagate_bases) / sizeof (unsigned int)); ++i) {
			void __iomem *p = ioremap(seagate_bases[i], 0x2000);
			if (!p)
				continue;
			for (j = 0; j < NUM_SIGNATURES; ++j)
				if (check_signature(p + signatures[j].offset, signatures[j].signature, signatures[j].length)) {
					base_address = seagate_bases[i];
					controller_type = signatures[j].type;
					break;
				}
			iounmap(p);
		}
#endif				/* OVERRIDE */
	}
	/* (! controller_type) */
	tpnt->this_id = (controller_type == SEAGATE) ? 7 : 6;
	tpnt->name = (controller_type == SEAGATE) ? ST0X_ID_STR : FD_ID_STR;

	if (!base_address) {
		printk(KERN_INFO "seagate: ST0x/TMC-8xx not detected.\n");
		return 0;
	}

	cr = base_address + (controller_type == SEAGATE ? 0x1a00 : 0x1c00);
	dr = cr + 0x200;
	st0x_cr_sr = ioremap(cr, 0x100);
	st0x_dr = ioremap(dr, 0x100);

	DANY("%s detected. Base address = %x, cr = %x, dr = %x\n",
	      tpnt->name, base_address, cr, dr);

	/*
	 *	At all times, we will use IRQ 5.  Should also check for IRQ3
	 *	if we lose our first interrupt.
	 */
	instance = scsi_register (tpnt, 0);
	if (instance == NULL)
		return 0;

	hostno = instance->host_no;
	if (request_irq (irq, do_seagate_reconnect_intr, SA_INTERRUPT, (controller_type == SEAGATE) ? "seagate" : "tmc-8xx", instance)) {
		printk(KERN_ERR "scsi%d : unable to allocate IRQ%d\n", hostno, irq);
		return 0;
	}
	instance->irq = irq;
	instance->io_port = base_address;
#ifdef SLOW_RATE
	printk(KERN_INFO "Calibrating borken timer... ");
	borken_init();
	printk(" %d cycles per transfer\n", borken_calibration);
#endif
	printk (KERN_INFO "This is one second... ");
	{
		int clock;
		ULOOP (1 * 1000 * 1000) {
			STATUS;
			if (TIMEOUT)
				break;
		}
	}

	printk ("done, %s options:"
#ifdef ARBITRATE
		" ARBITRATE"
#endif
#ifdef DEBUG
		" DEBUG"
#endif
#ifdef FAST
		" FAST"
#ifdef FAST32
		"32"
#endif
#endif
#ifdef LINKED
		" LINKED"
#endif
#ifdef PARITY
		" PARITY"
#endif
#ifdef SEAGATE_USE_ASM
		" SEAGATE_USE_ASM"
#endif
#ifdef SLOW_RATE
		" SLOW_RATE"
#endif
#ifdef SWAPSTAT
		" SWAPSTAT"
#endif
#ifdef SWAPCNTDATA
		" SWAPCNTDATA"
#endif
		"\n", tpnt->name);
	return 1;
}

static const char *seagate_st0x_info (struct Scsi_Host *shpnt)
{
	static char buffer[64];

	snprintf(buffer, 64, "%s at irq %d, address 0x%05X",
		 (controller_type == SEAGATE) ? ST0X_ID_STR : FD_ID_STR,
		 irq, base_address);
	return buffer;
}

/*
 * These are our saved pointers for the outstanding command that is
 * waiting for a reconnect
 */

static unsigned char current_target, current_lun;
static unsigned char *current_cmnd, *current_data;
static int current_nobuffs;
static struct scatterlist *current_buffer;
static int current_bufflen;

#ifdef LINKED
/*
 * linked_connected indicates whether or not we are currently connected to
 * linked_target, linked_lun and in an INFORMATION TRANSFER phase,
 * using linked commands.
 */

static int linked_connected = 0;
static unsigned char linked_target, linked_lun;
#endif

static void (*done_fn) (Scsi_Cmnd *) = NULL;
static Scsi_Cmnd *SCint = NULL;

/*
 * These control whether or not disconnect / reconnect will be attempted,
 * or are being attempted.
 */

#define NO_RECONNECT    0
#define RECONNECT_NOW   1
#define CAN_RECONNECT   2

/*
 * LINKED_RIGHT indicates that we are currently connected to the correct target
 * for this command, LINKED_WRONG indicates that we are connected to the wrong
 * target. Note that these imply CAN_RECONNECT and require defined(LINKED).
 */

#define LINKED_RIGHT    3
#define LINKED_WRONG    4

/*
 * This determines if we are expecting to reconnect or not.
 */

static int should_reconnect = 0;

/*
 * The seagate_reconnect_intr routine is called when a target reselects the
 * host adapter.  This occurs on the interrupt triggered by the target
 * asserting SEL.
 */

static irqreturn_t do_seagate_reconnect_intr(int irq, void *dev_id,
						struct pt_regs *regs)
{
	unsigned long flags;
	struct Scsi_Host *dev = dev_id;
	
	spin_lock_irqsave (dev->host_lock, flags);
	seagate_reconnect_intr (irq, dev_id, regs);
	spin_unlock_irqrestore (dev->host_lock, flags);
	return IRQ_HANDLED;
}

static void seagate_reconnect_intr (int irq, void *dev_id, struct pt_regs *regs)
{
	int temp;
	Scsi_Cmnd *SCtmp;

	DPRINTK (PHASE_RESELECT, "scsi%d : seagate_reconnect_intr() called\n", hostno);

	if (!should_reconnect)
		printk(KERN_WARNING "scsi%d: unexpected interrupt.\n", hostno);
	else {
		should_reconnect = 0;

		DPRINTK (PHASE_RESELECT, "scsi%d : internal_command(%d, %08x, %08x, RECONNECT_NOW\n", 
			hostno, current_target, current_data, current_bufflen);

		temp = internal_command (current_target, current_lun, current_cmnd, current_data, current_bufflen, RECONNECT_NOW);

		if (msg_byte(temp) != DISCONNECT) {
			if (done_fn) {
				DPRINTK(PHASE_RESELECT, "scsi%d : done_fn(%d,%08x)", hostno, hostno, temp);
				if (!SCint)
					panic ("SCint == NULL in seagate");
				SCtmp = SCint;
				SCint = NULL;
				SCtmp->result = temp;
				done_fn(SCtmp);
			} else
				printk(KERN_ERR "done_fn() not defined.\n");
		}
	}
}

/*
 * The seagate_st0x_queue_command() function provides a queued interface
 * to the seagate SCSI driver.  Basically, it just passes control onto the
 * seagate_command() function, after fixing it so that the done_fn()
 * is set to the one passed to the function.  We have to be very careful,
 * because there are some commands on some devices that do not disconnect,
 * and if we simply call the done_fn when the command is done then another
 * command is started and queue_command is called again...  We end up
 * overflowing the kernel stack, and this tends not to be such a good idea.
 */

static int recursion_depth = 0;

static int seagate_st0x_queue_command (Scsi_Cmnd * SCpnt, void (*done) (Scsi_Cmnd *))
{
	int result, reconnect;
	Scsi_Cmnd *SCtmp;

	DANY ("seagate: que_command");
	done_fn = done;
	current_target = SCpnt->device->id;
	current_lun = SCpnt->device->lun;
	current_cmnd = SCpnt->cmnd;
	current_data = (unsigned char *) SCpnt->request_buffer;
	current_bufflen = SCpnt->request_bufflen;
	SCint = SCpnt;
	if (recursion_depth)
		return 1;
	recursion_depth++;
	do {
#ifdef LINKED
		/*
		 * Set linked command bit in control field of SCSI command.
		 */

		current_cmnd[SCpnt->cmd_len] |= 0x01;
		if (linked_connected) {
			DPRINTK (DEBUG_LINKED, "scsi%d : using linked commands, current I_T_L nexus is ", hostno);
			if (linked_target == current_target && linked_lun == current_lun) 
			{
				DPRINTK(DEBUG_LINKED, "correct\n");
				reconnect = LINKED_RIGHT;
			} else {
				DPRINTK(DEBUG_LINKED, "incorrect\n");
				reconnect = LINKED_WRONG;
			}
		} else
#endif				/* LINKED */
			reconnect = CAN_RECONNECT;

		result = internal_command(SCint->device->id, SCint->device->lun, SCint->cmnd,
				      SCint->request_buffer, SCint->request_bufflen, reconnect);
		if (msg_byte(result) == DISCONNECT)
			break;
		SCtmp = SCint;
		SCint = NULL;
		SCtmp->result = result;
		done_fn(SCtmp);
	}
	while (SCint);
	recursion_depth--;
	return 0;
}

static int internal_command (unsigned char target, unsigned char lun,
		  const void *cmnd, void *buff, int bufflen, int reselect)
{
	unsigned char *data = NULL;
	struct scatterlist *buffer = NULL;
	int clock, temp, nobuffs = 0, done = 0, len = 0;
#ifdef DEBUG
	int transfered = 0, phase = 0, newphase;
#endif
	register unsigned char status_read;
	unsigned char tmp_data, tmp_control, status = 0, message = 0;
	unsigned transfersize = 0, underflow = 0;
#ifdef SLOW_RATE
	int borken = (int) SCint->device->borken;	/* Does the current target require
							   Very Slow I/O ?  */
#endif

	incommand = 0;
	st0x_aborted = 0;

#if (DEBUG & PRINT_COMMAND)
	printk("scsi%d : target = %d, command = ", hostno, target);
	__scsi_print_command((unsigned char *) cmnd);
#endif

#if (DEBUG & PHASE_RESELECT)
	switch (reselect) {
	case RECONNECT_NOW:
		printk("scsi%d : reconnecting\n", hostno);
		break;
#ifdef LINKED
	case LINKED_RIGHT:
		printk("scsi%d : connected, can reconnect\n", hostno);
		break;
	case LINKED_WRONG:
		printk("scsi%d : connected to wrong target, can reconnect\n",
			hostno);
		break;
#endif
	case CAN_RECONNECT:
		printk("scsi%d : allowed to reconnect\n", hostno);
		break;
	default:
		printk("scsi%d : not allowed to reconnect\n", hostno);
	}
#endif

	if (target == (controller_type == SEAGATE ? 7 : 6))
		return DID_BAD_TARGET;

	/*
	 *	We work it differently depending on if this is is "the first time,"
	 *      or a reconnect.  If this is a reselect phase, then SEL will
	 *      be asserted, and we must skip selection / arbitration phases.
	 */

	switch (reselect) {
	case RECONNECT_NOW:
		DPRINTK (PHASE_RESELECT, "scsi%d : phase RESELECT \n", hostno);
		/*
		 *	At this point, we should find the logical or of our ID
		 *	and the original target's ID on the BUS, with BSY, SEL,
		 *	and I/O signals asserted.
		 *
		 *      After ARBITRATION phase is completed, only SEL, BSY,
		 *	and the target ID are asserted.  A valid initiator ID
		 *	is not on the bus until IO is asserted, so we must wait
		 *	for that.
		 */
		ULOOP (100 * 1000) {
			temp = STATUS;
			if ((temp & STAT_IO) && !(temp & STAT_BSY))
				break;
			if (TIMEOUT) {
				DPRINTK (PHASE_RESELECT, "scsi%d : RESELECT timed out while waiting for IO .\n", hostno);
				return (DID_BAD_INTR << 16);
			}
		}

		/*
		 *	After I/O is asserted by the target, we can read our ID
		 *	and its ID off of the BUS.
		 */

		if (!((temp = DATA) & (controller_type == SEAGATE ? 0x80 : 0x40))) {
			DPRINTK (PHASE_RESELECT, "scsi%d : detected reconnect request to different target.\n\tData bus = %d\n", hostno, temp);
			return (DID_BAD_INTR << 16);
		}

		if (!(temp & (1 << current_target))) {
			printk(KERN_WARNING "scsi%d : Unexpected reselect interrupt.  Data bus = %d\n", hostno, temp);
			return (DID_BAD_INTR << 16);
		}

		buffer = current_buffer;
		cmnd = current_cmnd;	/* WDE add */
		data = current_data;	/* WDE add */
		len = current_bufflen;	/* WDE add */
		nobuffs = current_nobuffs;

		/*
		 *	We have determined that we have been selected.  At this
		 *	point, we must respond to the reselection by asserting
		 *	BSY ourselves
		 */

#if 1