DcTrackerBase.java revision 63dce7fe9678c4610a410ebddd49518190f90386
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.telephony.dataconnection;
18
19import android.app.AlarmManager;
20import android.app.PendingIntent;
21import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
26import android.content.SharedPreferences;
27import android.database.ContentObserver;
28import android.net.ConnectivityManager;
29import android.net.LinkCapabilities;
30import android.net.LinkProperties;
31import android.net.NetworkInfo;
32import android.net.TrafficStats;
33import android.net.wifi.WifiManager;
34import android.os.AsyncResult;
35import android.os.Build;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.HandlerThread;
39import android.os.Message;
40import android.os.Messenger;
41import android.os.SystemClock;
42import android.os.SystemProperties;
43import android.preference.PreferenceManager;
44import android.provider.Settings;
45import android.provider.Settings.SettingNotFoundException;
46import android.telephony.TelephonyManager;
47import android.text.TextUtils;
48import android.util.EventLog;
49import android.telephony.Rlog;
50
51import com.android.internal.R;
52import com.android.internal.telephony.DctConstants;
53import com.android.internal.telephony.DctConstants.State;
54import com.android.internal.telephony.EventLogTags;
55import com.android.internal.telephony.Phone;
56import com.android.internal.telephony.PhoneBase;
57import com.android.internal.telephony.PhoneConstants;
58import com.android.internal.telephony.uicc.IccRecords;
59import com.android.internal.telephony.uicc.UiccController;
60import com.android.internal.util.AsyncChannel;
61import com.android.internal.util.ArrayUtils;
62
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
65import java.util.ArrayList;
66import java.util.Comparator;
67import java.util.HashMap;
68import java.util.Map.Entry;
69import java.util.Set;
70import java.util.concurrent.ConcurrentHashMap;
71import java.util.concurrent.atomic.AtomicInteger;
72import java.util.concurrent.atomic.AtomicReference;
73import java.util.PriorityQueue;
74
75/**
76 * {@hide}
77 */
78public abstract class DcTrackerBase extends Handler {
79    protected static final boolean DBG = true;
80    protected static final boolean VDBG = false; // STOPSHIP if true
81    protected static final boolean VDBG_STALL = true; // STOPSHIP if true
82    protected static final boolean RADIO_TESTS = false;
83
84    /**
85     * Constants for the data connection activity:
86     * physical link down/up
87     */
88    protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_INACTIVE = 0;
89    protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_DOWN = 1;
90    protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_UP = 2;
91
92    /** Delay between APN attempts.
93        Note the property override mechanism is there just for testing purpose only. */
94    protected static final int APN_DELAY_DEFAULT_MILLIS = 20000;
95
96    /** Delay between APN attempts when in fail fast mode */
97    protected static final int APN_FAIL_FAST_DELAY_DEFAULT_MILLIS = 3000;
98
99    AlarmManager mAlarmManager;
100
101    protected Object mDataEnabledLock = new Object();
102
103    // responds to the setInternalDataEnabled call - used internally to turn off data
104    // for example during emergency calls
105    protected boolean mInternalDataEnabled = true;
106
107    // responds to public (user) API to enable/disable data use
108    // independent of mInternalDataEnabled and requests for APN access
109    // persisted
110    protected boolean mUserDataEnabled = true;
111
112    // TODO: move away from static state once 5587429 is fixed.
113    protected static boolean sPolicyDataEnabled = true;
114
115    private boolean[] mDataEnabled = new boolean[DctConstants.APN_NUM_TYPES];
116
117    private int mEnabledCount = 0;
118
119    /* Currently requested APN type (TODO: This should probably be a parameter not a member) */
120    protected String mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
121
122    /** Retry configuration: A doubling of retry times from 5secs to 30minutes */
123    protected static final String DEFAULT_DATA_RETRY_CONFIG = "default_randomization=2000,"
124        + "5000,10000,20000,40000,80000:5000,160000:5000,"
125        + "320000:5000,640000:5000,1280000:5000,1800000:5000";
126
127    /** Retry configuration for secondary networks: 4 tries in 20 sec */
128    protected static final String SECONDARY_DATA_RETRY_CONFIG =
129            "max_retries=3, 5000, 5000, 5000";
130
131    /** Slow poll when attempting connection recovery. */
132    protected static final int POLL_NETSTAT_SLOW_MILLIS = 5000;
133    /** Default max failure count before attempting to network re-registration. */
134    protected static final int DEFAULT_MAX_PDP_RESET_FAIL = 3;
135
136    /**
137     * After detecting a potential connection problem, this is the max number
138     * of subsequent polls before attempting recovery.
139     */
140    protected static final int NO_RECV_POLL_LIMIT = 24;
141    // 1 sec. default polling interval when screen is on.
142    protected static final int POLL_NETSTAT_MILLIS = 1000;
143    // 10 min. default polling interval when screen is off.
144    protected static final int POLL_NETSTAT_SCREEN_OFF_MILLIS = 1000*60*10;
145    // 2 min for round trip time
146    protected static final int POLL_LONGEST_RTT = 120 * 1000;
147    // Default sent packets without ack which triggers initial recovery steps
148    protected static final int NUMBER_SENT_PACKETS_OF_HANG = 10;
149    // how long to wait before switching back to default APN
150    protected static final int RESTORE_DEFAULT_APN_DELAY = 1 * 60 * 1000;
151    // system property that can override the above value
152    protected static final String APN_RESTORE_DELAY_PROP_NAME = "android.telephony.apn-restore";
153    // represents an invalid IP address
154    protected static final String NULL_IP = "0.0.0.0";
155
156    // Default for the data stall alarm while non-aggressive stall detection
157    protected static final int DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT = 1000 * 60 * 6;
158    // Default for the data stall alarm for aggressive stall detection
159    protected static final int DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT = 1000 * 60;
160    // If attempt is less than this value we're doing first level recovery
161    protected static final int DATA_STALL_NO_RECV_POLL_LIMIT = 1;
162    // Tag for tracking stale alarms
163    protected static final String DATA_STALL_ALARM_TAG_EXTRA = "data.stall.alram.tag";
164
165    protected static final boolean DATA_STALL_SUSPECTED = true;
166    protected static final boolean DATA_STALL_NOT_SUSPECTED = false;
167
168    protected String RADIO_RESET_PROPERTY = "gsm.radioreset";
169
170    protected static final String INTENT_RECONNECT_ALARM =
171            "com.android.internal.telephony.data-reconnect";
172    protected static final String INTENT_RECONNECT_ALARM_EXTRA_TYPE = "reconnect_alarm_extra_type";
173    protected static final String INTENT_RECONNECT_ALARM_EXTRA_REASON =
174            "reconnect_alarm_extra_reason";
175
176    protected static final String INTENT_RESTART_TRYSETUP_ALARM =
177            "com.android.internal.telephony.data-restart-trysetup";
178    protected static final String INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE =
179            "restart_trysetup_alarm_extra_type";
180
181    protected static final String INTENT_DATA_STALL_ALARM =
182            "com.android.internal.telephony.data-stall";
183
184
185
186    protected static final String DEFALUT_DATA_ON_BOOT_PROP = "net.def_data_on_boot";
187
188    protected DcTesterFailBringUpAll mDcTesterFailBringUpAll;
189    protected DcController mDcc;
190
191    // member variables
192    protected PhoneBase mPhone;
193    protected UiccController mUiccController;
194    protected AtomicReference<IccRecords> mIccRecords = new AtomicReference<IccRecords>();
195    protected DctConstants.Activity mActivity = DctConstants.Activity.NONE;
196    protected DctConstants.State mState = DctConstants.State.IDLE;
197    protected Handler mDataConnectionTracker = null;
198
199    protected long mTxPkts;
200    protected long mRxPkts;
201    protected int mNetStatPollPeriod;
202    protected boolean mNetStatPollEnabled = false;
203
204    protected TxRxSum mDataStallTxRxSum = new TxRxSum(0, 0);
205    // Used to track stale data stall alarms.
206    protected int mDataStallAlarmTag = (int) SystemClock.elapsedRealtime();
207    // The current data stall alarm intent
208    protected PendingIntent mDataStallAlarmIntent = null;
209    // Number of packets sent since the last received packet
210    protected long mSentSinceLastRecv;
211    // Controls when a simple recovery attempt it to be tried
212    protected int mNoRecvPollCount = 0;
213    // Refrence counter for enabling fail fast
214    protected static int sEnableFailFastRefCounter = 0;
215    // True if data stall detection is enabled
216    protected volatile boolean mDataStallDetectionEnabled = true;
217
218    protected volatile boolean mFailFast = false;
219
220    // True when in voice call
221    protected boolean mInVoiceCall = false;
222
223    // wifi connection status will be updated by sticky intent
224    protected boolean mIsWifiConnected = false;
225
226    /** Intent sent when the reconnect alarm fires. */
227    protected PendingIntent mReconnectIntent = null;
228
229    /** CID of active data connection */
230    protected int mCidActive;
231
232    // When false we will not auto attach and manually attaching is required.
233    protected boolean mAutoAttachOnCreation = false;
234
235    // State of screen
236    // (TODO: Reconsider tying directly to screen, maybe this is
237    //        really a lower power mode")
238    protected boolean mIsScreenOn = true;
239
240    /** Allows the generation of unique Id's for DataConnection objects */
241    protected AtomicInteger mUniqueIdGenerator = new AtomicInteger(0);
242
243    /** The data connections. */
244    protected HashMap<Integer, DataConnection> mDataConnections =
245        new HashMap<Integer, DataConnection>();
246
247    /** The data connection async channels */
248    protected HashMap<Integer, DcAsyncChannel> mDataConnectionAcHashMap =
249        new HashMap<Integer, DcAsyncChannel>();
250
251    /** Convert an ApnType string to Id (TODO: Use "enumeration" instead of String for ApnType) */
252    protected HashMap<String, Integer> mApnToDataConnectionId =
253                                    new HashMap<String, Integer>();
254
255    /** Phone.APN_TYPE_* ===> ApnContext */
256    protected final ConcurrentHashMap<String, ApnContext> mApnContexts =
257                                    new ConcurrentHashMap<String, ApnContext>();
258
259    /** kept in sync with mApnContexts
260     * Higher numbers are higher priority and sorted so highest priority is first */
261    protected final PriorityQueue<ApnContext>mPrioritySortedApnContexts =
262            new PriorityQueue<ApnContext>(5,
263            new Comparator<ApnContext>() {
264                public int compare(ApnContext c1, ApnContext c2) {
265                    return c2.priority - c1.priority;
266                }
267            } );
268
269    /* Currently active APN */
270    protected ApnSetting mActiveApn;
271
272    /** allApns holds all apns */
273    protected ArrayList<ApnSetting> mAllApnSettings = null;
274
275    /** preferred apn */
276    protected ApnSetting mPreferredApn = null;
277
278    /** Is packet service restricted by network */
279    protected boolean mIsPsRestricted = false;
280
281    /* Once disposed dont handle any messages */
282    protected boolean mIsDisposed = false;
283
284    protected ContentResolver mResolver;
285
286    /* Set to true with CMD_ENABLE_MOBILE_PROVISIONING */
287    protected boolean mIsProvisioning = false;
288
289    /* The Url passed as object parameter in CMD_ENABLE_MOBILE_PROVISIONING */
290    protected String mProvisioningUrl = null;
291
292    /* Intent for the provisioning apn alarm */
293    protected static final String INTENT_PROVISIONING_APN_ALARM =
294            "com.android.internal.telephony.provisioning_apn_alarm";
295
296    /* Tag for tracking stale alarms */
297    protected static final String PROVISIONING_APN_ALARM_TAG_EXTRA = "provisioning.apn.alarm.tag";
298
299    /* Debug property for overriding the PROVISIONING_APN_ALARM_DELAY_IN_MS */
300    protected static final String DEBUG_PROV_APN_ALARM =
301            "persist.debug.prov_apn_alarm";
302
303    /* Default for the provisioning apn alarm timeout */
304    protected static final int PROVISIONING_APN_ALARM_DELAY_IN_MS_DEFAULT = 1000 * 60 * 15;
305
306    /* The provision apn alarm intent used to disable the provisioning apn */
307    protected PendingIntent mProvisioningApnAlarmIntent = null;
308
309    /* Used to track stale provisioning apn alarms */
310    protected int mProvisioningApnAlarmTag = (int) SystemClock.elapsedRealtime();
311
312    protected AsyncChannel mReplyAc = new AsyncChannel();
313
314    protected BroadcastReceiver mIntentReceiver = new BroadcastReceiver ()
315    {
316        @Override
317        public void onReceive(Context context, Intent intent)
318        {
319            String action = intent.getAction();
320            if (DBG) log("onReceive: action=" + action);
321            if (action.equals(Intent.ACTION_SCREEN_ON)) {
322                mIsScreenOn = true;
323                stopNetStatPoll();
324                startNetStatPoll();
325                restartDataStallAlarm();
326            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
327                mIsScreenOn = false;
328                stopNetStatPoll();
329                startNetStatPoll();
330                restartDataStallAlarm();
331            } else if (action.startsWith(INTENT_RECONNECT_ALARM)) {
332                if (DBG) log("Reconnect alarm. Previous state was " + mState);
333                onActionIntentReconnectAlarm(intent);
334            } else if (action.startsWith(INTENT_RESTART_TRYSETUP_ALARM)) {
335                if (DBG) log("Restart trySetup alarm");
336                onActionIntentRestartTrySetupAlarm(intent);
337            } else if (action.equals(INTENT_DATA_STALL_ALARM)) {
338                onActionIntentDataStallAlarm(intent);
339            } else if (action.equals(INTENT_PROVISIONING_APN_ALARM)) {
340                onActionIntentProvisioningApnAlarm(intent);
341            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
342                final android.net.NetworkInfo networkInfo = (NetworkInfo)
343                        intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
344                mIsWifiConnected = (networkInfo != null && networkInfo.isConnected());
345                if (DBG) log("NETWORK_STATE_CHANGED_ACTION: mIsWifiConnected=" + mIsWifiConnected);
346            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
347                final boolean enabled = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
348                        WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_ENABLED;
349
350                if (!enabled) {
351                    // when WiFi got disabled, the NETWORK_STATE_CHANGED_ACTION
352                    // quit and won't report disconnected until next enabling.
353                    mIsWifiConnected = false;
354                }
355                if (DBG) log("WIFI_STATE_CHANGED_ACTION: enabled=" + enabled
356                        + " mIsWifiConnected=" + mIsWifiConnected);
357            }
358        }
359    };
360
361    private Runnable mPollNetStat = new Runnable()
362    {
363        @Override
364        public void run() {
365            updateDataActivity();
366
367            if (mIsScreenOn) {
368                mNetStatPollPeriod = Settings.Global.getInt(mResolver,
369                        Settings.Global.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS);
370            } else {
371                mNetStatPollPeriod = Settings.Global.getInt(mResolver,
372                        Settings.Global.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS,
373                        POLL_NETSTAT_SCREEN_OFF_MILLIS);
374            }
375
376            if (mNetStatPollEnabled) {
377                mDataConnectionTracker.postDelayed(this, mNetStatPollPeriod);
378            }
379        }
380    };
381
382    private class DataRoamingSettingObserver extends ContentObserver {
383
384        public DataRoamingSettingObserver(Handler handler, Context context) {
385            super(handler);
386            mResolver = context.getContentResolver();
387        }
388
389        public void register() {
390            mResolver.registerContentObserver(
391                    Settings.Global.getUriFor(Settings.Global.DATA_ROAMING), false, this);
392        }
393
394        public void unregister() {
395            mResolver.unregisterContentObserver(this);
396        }
397
398        @Override
399        public void onChange(boolean selfChange) {
400            // already running on mPhone handler thread
401            if (mPhone.getServiceState().getRoaming()) {
402                sendMessage(obtainMessage(DctConstants.EVENT_ROAMING_ON));
403            }
404        }
405    }
406    private final DataRoamingSettingObserver mDataRoamingSettingObserver;
407
408    /**
409     * The Initial MaxRetry sent to a DataConnection as a parameter
410     * to DataConnectionAc.bringUp. This value can be defined at compile
411     * time using the SystemProperty Settings.Global.DCT_INITIAL_MAX_RETRY
412     * and at runtime using gservices to change Settings.Global.DCT_INITIAL_MAX_RETRY.
413     */
414    private static final int DEFAULT_MDC_INITIAL_RETRY = 1;
415    protected int getInitialMaxRetry() {
416        if (mFailFast) {
417            return 0;
418        }
419        // Get default value from system property or use DEFAULT_MDC_INITIAL_RETRY
420        int value = SystemProperties.getInt(
421                Settings.Global.MDC_INITIAL_MAX_RETRY, DEFAULT_MDC_INITIAL_RETRY);
422
423        // Check if its been overridden
424        return Settings.Global.getInt(mResolver,
425                Settings.Global.MDC_INITIAL_MAX_RETRY, value);
426    }
427
428    /**
429     * Maintain the sum of transmit and receive packets.
430     *
431     * The packet counts are initialized and reset to -1 and
432     * remain -1 until they can be updated.
433     */
434    public class TxRxSum {
435        public long txPkts;
436        public long rxPkts;
437
438        public TxRxSum() {
439            reset();
440        }
441
442        public TxRxSum(long txPkts, long rxPkts) {
443            this.txPkts = txPkts;
444            this.rxPkts = rxPkts;
445        }
446
447        public TxRxSum(TxRxSum sum) {
448            txPkts = sum.txPkts;
449            rxPkts = sum.rxPkts;
450        }
451
452        public void reset() {
453            txPkts = -1;
454            rxPkts = -1;
455        }
456
457        @Override
458        public String toString() {
459            return "{txSum=" + txPkts + " rxSum=" + rxPkts + "}";
460        }
461
462        public void updateTxRxSum() {
463            this.txPkts = TrafficStats.getMobileTcpTxPackets();
464            this.rxPkts = TrafficStats.getMobileTcpRxPackets();
465        }
466    }
467
468    protected void onActionIntentReconnectAlarm(Intent intent) {
469        String reason = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON);
470        String apnType = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_TYPE);
471
472        ApnContext apnContext = mApnContexts.get(apnType);
473
474        if (DBG) {
475            log("onActionIntentReconnectAlarm: mState=" + mState + " reason=" + reason +
476                    " apnType=" + apnType + " apnContext=" + apnContext +
477                    " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap);
478        }
479
480        if ((apnContext != null) && (apnContext.isEnabled())) {
481            apnContext.setReason(reason);
482            DctConstants.State apnContextState = apnContext.getState();
483            if (DBG) {
484                log("onActionIntentReconnectAlarm: apnContext state=" + apnContextState);
485            }
486            if ((apnContextState == DctConstants.State.FAILED)
487                    || (apnContextState == DctConstants.State.IDLE)) {
488                if (DBG) {
489                    log("onActionIntentReconnectAlarm: state is FAILED|IDLE, disassociate");
490                }
491                DcAsyncChannel dcac = apnContext.getDcAc();
492                if (dcac != null) {
493                    dcac.tearDown(apnContext, "", null);
494                }
495                apnContext.setDataConnectionAc(null);
496                apnContext.setState(DctConstants.State.IDLE);
497            } else {
498                if (DBG) log("onActionIntentReconnectAlarm: keep associated");
499            }
500            // TODO: IF already associated should we send the EVENT_TRY_SETUP_DATA???
501            sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext));
502
503            apnContext.setReconnectIntent(null);
504        }
505    }
506
507    protected void onActionIntentRestartTrySetupAlarm(Intent intent) {
508        String apnType = intent.getStringExtra(INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE);
509        ApnContext apnContext = mApnContexts.get(apnType);
510        if (DBG) {
511            log("onActionIntentRestartTrySetupAlarm: mState=" + mState +
512                    " apnType=" + apnType + " apnContext=" + apnContext +
513                    " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap);
514        }
515        sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext));
516    }
517
518    protected void onActionIntentDataStallAlarm(Intent intent) {
519        if (VDBG_STALL) log("onActionIntentDataStallAlarm: action=" + intent.getAction());
520        Message msg = obtainMessage(DctConstants.EVENT_DATA_STALL_ALARM,
521                intent.getAction());
522        msg.arg1 = intent.getIntExtra(DATA_STALL_ALARM_TAG_EXTRA, 0);
523        sendMessage(msg);
524    }
525
526    ConnectivityManager mCm;
527
528    /**
529     * Default constructor
530     */
531    protected DcTrackerBase(PhoneBase phone) {
532        super();
533        if (DBG) log("DCT.constructor");
534        mPhone = phone;
535        mResolver = mPhone.getContext().getContentResolver();
536        mUiccController = UiccController.getInstance();
537        mUiccController.registerForIccChanged(this, DctConstants.EVENT_ICC_CHANGED, null);
538        mAlarmManager =
539                (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE);
540        mCm = (ConnectivityManager) mPhone.getContext().getSystemService(
541                Context.CONNECTIVITY_SERVICE);
542
543
544        IntentFilter filter = new IntentFilter();
545        filter.addAction(Intent.ACTION_SCREEN_ON);
546        filter.addAction(Intent.ACTION_SCREEN_OFF);
547        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
548        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
549        filter.addAction(INTENT_DATA_STALL_ALARM);
550        filter.addAction(INTENT_PROVISIONING_APN_ALARM);
551
552        mUserDataEnabled = Settings.Global.getInt(
553                mPhone.getContext().getContentResolver(), Settings.Global.MOBILE_DATA, 1) == 1;
554
555        mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);
556
557        // This preference tells us 1) initial condition for "dataEnabled",
558        // and 2) whether the RIL will setup the baseband to auto-PS attach.
559
560        mDataEnabled[DctConstants.APN_DEFAULT_ID] =
561                SystemProperties.getBoolean(DEFALUT_DATA_ON_BOOT_PROP,true);
562        if (mDataEnabled[DctConstants.APN_DEFAULT_ID]) {
563            mEnabledCount++;
564        }
565
566        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
567        mAutoAttachOnCreation = sp.getBoolean(PhoneBase.DATA_DISABLED_ON_BOOT_KEY, false);
568
569        // Watch for changes to Settings.Global.DATA_ROAMING
570        mDataRoamingSettingObserver = new DataRoamingSettingObserver(mPhone, mPhone.getContext());
571        mDataRoamingSettingObserver.register();
572
573        HandlerThread dcHandlerThread = new HandlerThread("DcHandlerThread");
574        dcHandlerThread.start();
575        Handler dcHandler = new Handler(dcHandlerThread.getLooper());
576        mDcc = DcController.makeDcc(mPhone, this, dcHandler);
577        mDcTesterFailBringUpAll = new DcTesterFailBringUpAll(mPhone, dcHandler);
578    }
579
580    public void dispose() {
581        if (DBG) log("DCT.dispose");
582        for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) {
583            dcac.disconnect();
584        }
585        mDataConnectionAcHashMap.clear();
586        mIsDisposed = true;
587        mPhone.getContext().unregisterReceiver(mIntentReceiver);
588        mUiccController.unregisterForIccChanged(this);
589        mDataRoamingSettingObserver.unregister();
590        mDcc.dispose();
591        mDcTesterFailBringUpAll.dispose();
592    }
593
594    public DctConstants.Activity getActivity() {
595        return mActivity;
596    }
597
598    public boolean isApnTypeActive(String type) {
599        // TODO: support simultaneous with List instead
600        if (PhoneConstants.APN_TYPE_DUN.equals(type)) {
601            ApnSetting dunApn = fetchDunApn();
602            if (dunApn != null) {
603                return ((mActiveApn != null) && (dunApn.toString().equals(mActiveApn.toString())));
604            }
605        }
606        return mActiveApn != null && mActiveApn.canHandleType(type);
607    }
608
609    protected ApnSetting fetchDunApn() {
610        if (SystemProperties.getBoolean("net.tethering.noprovisioning", false)) {
611            log("fetchDunApn: net.tethering.noprovisioning=true ret: null");
612            return null;
613        }
614        Context c = mPhone.getContext();
615        String apnData = Settings.Global.getString(c.getContentResolver(),
616                Settings.Global.TETHER_DUN_APN);
617        ApnSetting dunSetting = ApnSetting.fromString(apnData);
618        if (dunSetting != null) {
619            IccRecords r = mIccRecords.get();
620            String operator = (r != null) ? r.getOperatorNumeric() : "";
621            if (dunSetting.numeric.equals(operator)) {
622                if (VDBG) log("fetchDunApn: global TETHER_DUN_APN dunSetting=" + dunSetting);
623                return dunSetting;
624            }
625        }
626
627        apnData = c.getResources().getString(R.string.config_tether_apndata);
628        dunSetting = ApnSetting.fromString(apnData);
629        if (VDBG) log("fetchDunApn: config_tether_apndata dunSetting=" + dunSetting);
630        return dunSetting;
631    }
632
633    public String[] getActiveApnTypes() {
634        String[] result;
635        if (mActiveApn != null) {
636            result = mActiveApn.types;
637        } else {
638            result = new String[1];
639            result[0] = PhoneConstants.APN_TYPE_DEFAULT;
640        }
641        return result;
642    }
643
644    /** TODO: See if we can remove */
645    public String getActiveApnString(String apnType) {
646        String result = null;
647        if (mActiveApn != null) {
648            result = mActiveApn.apn;
649        }
650        return result;
651    }
652
653    /**
654     * Modify {@link android.provider.Settings.Global#DATA_ROAMING} value.
655     */
656    public void setDataOnRoamingEnabled(boolean enabled) {
657        if (getDataOnRoamingEnabled() != enabled) {
658            final ContentResolver resolver = mPhone.getContext().getContentResolver();
659            Settings.Global.putInt(resolver, Settings.Global.DATA_ROAMING, enabled ? 1 : 0);
660            // will trigger handleDataOnRoamingChange() through observer
661        }
662    }
663
664    /**
665     * Return current {@link android.provider.Settings.Global#DATA_ROAMING} value.
666     */
667    public boolean getDataOnRoamingEnabled() {
668        try {
669            final ContentResolver resolver = mPhone.getContext().getContentResolver();
670            return Settings.Global.getInt(resolver, Settings.Global.DATA_ROAMING) != 0;
671        } catch (SettingNotFoundException snfe) {
672            return false;
673        }
674    }
675
676    // abstract methods
677    protected abstract void restartRadio();
678    protected abstract void log(String s);
679    protected abstract void loge(String s);
680    protected abstract boolean isDataAllowed();
681    protected abstract boolean isApnTypeAvailable(String type);
682    public    abstract DctConstants.State getState(String apnType);
683    protected abstract boolean isProvisioningApn(String apnType);
684    protected abstract void setState(DctConstants.State s);
685    protected abstract void gotoIdleAndNotifyDataConnection(String reason);
686
687    protected abstract boolean onTrySetupData(String reason);
688    protected abstract void onRoamingOff();
689    protected abstract void onRoamingOn();
690    protected abstract void onRadioAvailable();
691    protected abstract void onRadioOffOrNotAvailable();
692    protected abstract void onDataSetupComplete(AsyncResult ar);
693    protected abstract void onDataSetupCompleteError(AsyncResult ar);
694    protected abstract void onDisconnectDone(int connId, AsyncResult ar);
695    protected abstract void onDisconnectDcRetrying(int connId, AsyncResult ar);
696    protected abstract void onVoiceCallStarted();
697    protected abstract void onVoiceCallEnded();
698    protected abstract void onCleanUpConnection(boolean tearDown, int apnId, String reason);
699    protected abstract void onCleanUpAllConnections(String cause);
700    public abstract boolean isDataPossible(String apnType);
701    protected abstract void onUpdateIcc();
702    protected abstract void completeConnection(ApnContext apnContext);
703
704    @Override
705    public void handleMessage(Message msg) {
706        switch (msg.what) {
707            case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
708                log("DISCONNECTED_CONNECTED: msg=" + msg);
709                DcAsyncChannel dcac = (DcAsyncChannel) msg.obj;
710                mDataConnectionAcHashMap.remove(dcac.getDataConnectionIdSync());
711                dcac.disconnected();
712                break;
713            }
714            case DctConstants.EVENT_ENABLE_NEW_APN:
715                onEnableApn(msg.arg1, msg.arg2);
716                break;
717
718            case DctConstants.EVENT_TRY_SETUP_DATA:
719                String reason = null;
720                if (msg.obj instanceof String) {
721                    reason = (String) msg.obj;
722                }
723                onTrySetupData(reason);
724                break;
725
726            case DctConstants.EVENT_DATA_STALL_ALARM:
727                onDataStallAlarm(msg.arg1);
728                break;
729
730            case DctConstants.EVENT_ROAMING_OFF:
731                onRoamingOff();
732                break;
733
734            case DctConstants.EVENT_ROAMING_ON:
735                onRoamingOn();
736                break;
737
738            case DctConstants.EVENT_RADIO_AVAILABLE:
739                onRadioAvailable();
740                break;
741
742            case DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
743                onRadioOffOrNotAvailable();
744                break;
745
746            case DctConstants.EVENT_DATA_SETUP_COMPLETE:
747                mCidActive = msg.arg1;
748                onDataSetupComplete((AsyncResult) msg.obj);
749                break;
750
751            case DctConstants.EVENT_DATA_SETUP_COMPLETE_ERROR:
752                onDataSetupCompleteError((AsyncResult) msg.obj);
753                break;
754
755            case DctConstants.EVENT_DISCONNECT_DONE:
756                log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DONE msg=" + msg);
757                onDisconnectDone(msg.arg1, (AsyncResult) msg.obj);
758                break;
759
760            case DctConstants.EVENT_DISCONNECT_DC_RETRYING:
761                log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DC_RETRYING msg=" + msg);
762                onDisconnectDcRetrying(msg.arg1, (AsyncResult) msg.obj);
763                break;
764
765            case DctConstants.EVENT_VOICE_CALL_STARTED:
766                onVoiceCallStarted();
767                break;
768
769            case DctConstants.EVENT_VOICE_CALL_ENDED:
770                onVoiceCallEnded();
771                break;
772
773            case DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS: {
774                onCleanUpAllConnections((String) msg.obj);
775                break;
776            }
777            case DctConstants.EVENT_CLEAN_UP_CONNECTION: {
778                boolean tearDown = (msg.arg1 == 0) ? false : true;
779                onCleanUpConnection(tearDown, msg.arg2, (String) msg.obj);
780                break;
781            }
782            case DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE: {
783                boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
784                onSetInternalDataEnabled(enabled);
785                break;
786            }
787            case DctConstants.EVENT_RESET_DONE: {
788                if (DBG) log("EVENT_RESET_DONE");
789                onResetDone((AsyncResult) msg.obj);
790                break;
791            }
792            case DctConstants.CMD_SET_USER_DATA_ENABLE: {
793                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
794                if (DBG) log("CMD_SET_USER_DATA_ENABLE enabled=" + enabled);
795                onSetUserDataEnabled(enabled);
796                break;
797            }
798            case DctConstants.CMD_SET_DEPENDENCY_MET: {
799                boolean met = (msg.arg1 == DctConstants.ENABLED) ? true : false;
800                if (DBG) log("CMD_SET_DEPENDENCY_MET met=" + met);
801                Bundle bundle = msg.getData();
802                if (bundle != null) {
803                    String apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY);
804                    if (apnType != null) {
805                        onSetDependencyMet(apnType, met);
806                    }
807                }
808                break;
809            }
810            case DctConstants.CMD_SET_POLICY_DATA_ENABLE: {
811                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
812                onSetPolicyDataEnabled(enabled);
813                break;
814            }
815            case DctConstants.CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: {
816                sEnableFailFastRefCounter += (msg.arg1 == DctConstants.ENABLED) ? 1 : -1;
817                if (DBG) {
818                    log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: "
819                            + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter);
820                }
821                if (sEnableFailFastRefCounter < 0) {
822                    final String s = "CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: "
823                            + "sEnableFailFastRefCounter:" + sEnableFailFastRefCounter + " < 0";
824                    loge(s);
825                    sEnableFailFastRefCounter = 0;
826                }
827                final boolean enabled = sEnableFailFastRefCounter > 0;
828                if (DBG) {
829                    log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: enabled=" + enabled
830                            + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter);
831                }
832                if (mFailFast != enabled) {
833                    mFailFast = enabled;
834                    mDataStallDetectionEnabled = !enabled;
835                    if (mDataStallDetectionEnabled
836                            && (getOverallState() == DctConstants.State.CONNECTED)
837                            && (!mInVoiceCall ||
838                                    mPhone.getServiceStateTracker()
839                                        .isConcurrentVoiceAndDataAllowed())) {
840                        if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: start data stall");
841                        stopDataStallAlarm();
842                        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
843                    } else {
844                        if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: stop data stall");
845                        stopDataStallAlarm();
846                    }
847                }
848
849                break;
850            }
851            case DctConstants.CMD_ENABLE_MOBILE_PROVISIONING: {
852                Bundle bundle = msg.getData();
853                if (bundle != null) {
854                    try {
855                        mProvisioningUrl = (String)bundle.get(DctConstants.PROVISIONING_URL_KEY);
856                    } catch(ClassCastException e) {
857                        loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioning url not a string" + e);
858                        mProvisioningUrl = null;
859                    }
860                }
861                if (TextUtils.isEmpty(mProvisioningUrl)) {
862                    loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioning url is empty, ignoring");
863                    mIsProvisioning = false;
864                    mProvisioningUrl = null;
865                } else {
866                    loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioningUrl=" + mProvisioningUrl);
867                    mIsProvisioning = true;
868                    startProvisioningApnAlarm();
869                }
870                break;
871            }
872            case DctConstants.EVENT_PROVISIONING_APN_ALARM: {
873                if (DBG) log("EVENT_PROVISIONING_APN_ALARM");
874                ApnContext apnCtx = mApnContexts.get("default");
875                if (apnCtx.isProvisioningApn() && apnCtx.isConnectedOrConnecting()) {
876                    if (mProvisioningApnAlarmTag == msg.arg1) {
877                        if (DBG) log("EVENT_PROVISIONING_APN_ALARM: Disconnecting");
878                        mIsProvisioning = false;
879                        mProvisioningUrl = null;
880                        stopProvisioningApnAlarm();
881                        sendCleanUpConnection(true, apnCtx);
882                    } else {
883                        if (DBG) {
884                            log("EVENT_PROVISIONING_APN_ALARM: ignore stale tag,"
885                                    + " mProvisioningApnAlarmTag:" + mProvisioningApnAlarmTag
886                                    + " != arg1:" + msg.arg1);
887                        }
888                    }
889                } else {
890                    if (DBG) log("EVENT_PROVISIONING_APN_ALARM: Not connected ignore");
891                }
892                break;
893            }
894            case DctConstants.CMD_IS_PROVISIONING_APN: {
895                if (DBG) log("CMD_IS_PROVISIONING_APN");
896                boolean isProvApn;
897                try {
898                    String apnType = null;
899                    Bundle bundle = msg.getData();
900                    if (bundle != null) {
901                        apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY);
902                    }
903                    if (TextUtils.isEmpty(apnType)) {
904                        loge("CMD_IS_PROVISIONING_APN: apnType is empty");
905                        isProvApn = false;
906                    } else {
907                        isProvApn = isProvisioningApn(apnType);
908                    }
909                } catch (ClassCastException e) {
910                    loge("CMD_IS_PROVISIONING_APN: NO provisioning url ignoring");
911                    isProvApn = false;
912                }
913                if (DBG) log("CMD_IS_PROVISIONING_APN: ret=" + isProvApn);
914                mReplyAc.replyToMessage(msg, DctConstants.CMD_IS_PROVISIONING_APN,
915                        isProvApn ? DctConstants.ENABLED : DctConstants.DISABLED);
916                break;
917            }
918            case DctConstants.EVENT_ICC_CHANGED: {
919                onUpdateIcc();
920                break;
921            }
922            case DctConstants.EVENT_RESTART_RADIO: {
923                restartRadio();
924                break;
925            }
926            default:
927                Rlog.e("DATA", "Unidentified event msg=" + msg);
928                break;
929        }
930    }
931
932    /**
933     * Report on whether data connectivity is enabled
934     *
935     * @return {@code false} if data connectivity has been explicitly disabled,
936     *         {@code true} otherwise.
937     */
938    public boolean getAnyDataEnabled() {
939        final boolean result;
940        synchronized (mDataEnabledLock) {
941            result = (mInternalDataEnabled && mUserDataEnabled && sPolicyDataEnabled
942                    && (mEnabledCount != 0));
943        }
944        if (!result && DBG) log("getAnyDataEnabled " + result);
945        return result;
946    }
947
948    protected boolean isEmergency() {
949        final boolean result;
950        synchronized (mDataEnabledLock) {
951            result = mPhone.isInEcm() || mPhone.isInEmergencyCall();
952        }
953        log("isEmergency: result=" + result);
954        return result;
955    }
956
957    protected int apnTypeToId(String type) {
958        if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DEFAULT)) {
959            return DctConstants.APN_DEFAULT_ID;
960        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_MMS)) {
961            return DctConstants.APN_MMS_ID;
962        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_SUPL)) {
963            return DctConstants.APN_SUPL_ID;
964        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DUN)) {
965            return DctConstants.APN_DUN_ID;
966        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_HIPRI)) {
967            return DctConstants.APN_HIPRI_ID;
968        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IMS)) {
969            return DctConstants.APN_IMS_ID;
970        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_FOTA)) {
971            return DctConstants.APN_FOTA_ID;
972        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_CBS)) {
973            return DctConstants.APN_CBS_ID;
974        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IA)) {
975            return DctConstants.APN_IA_ID;
976        } else {
977            return DctConstants.APN_INVALID_ID;
978        }
979    }
980
981    protected String apnIdToType(int id) {
982        switch (id) {
983        case DctConstants.APN_DEFAULT_ID:
984            return PhoneConstants.APN_TYPE_DEFAULT;
985        case DctConstants.APN_MMS_ID:
986            return PhoneConstants.APN_TYPE_MMS;
987        case DctConstants.APN_SUPL_ID:
988            return PhoneConstants.APN_TYPE_SUPL;
989        case DctConstants.APN_DUN_ID:
990            return PhoneConstants.APN_TYPE_DUN;
991        case DctConstants.APN_HIPRI_ID:
992            return PhoneConstants.APN_TYPE_HIPRI;
993        case DctConstants.APN_IMS_ID:
994            return PhoneConstants.APN_TYPE_IMS;
995        case DctConstants.APN_FOTA_ID:
996            return PhoneConstants.APN_TYPE_FOTA;
997        case DctConstants.APN_CBS_ID:
998            return PhoneConstants.APN_TYPE_CBS;
999        case DctConstants.APN_IA_ID:
1000            return PhoneConstants.APN_TYPE_IA;
1001        default:
1002            log("Unknown id (" + id + ") in apnIdToType");
1003            return PhoneConstants.APN_TYPE_DEFAULT;
1004        }
1005    }
1006
1007    public LinkProperties getLinkProperties(String apnType) {
1008        int id = apnTypeToId(apnType);
1009
1010        if (isApnIdEnabled(id)) {
1011            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
1012            return dcac.getLinkPropertiesSync();
1013        } else {
1014            return new LinkProperties();
1015        }
1016    }
1017
1018    public LinkCapabilities getLinkCapabilities(String apnType) {
1019        int id = apnTypeToId(apnType);
1020        if (isApnIdEnabled(id)) {
1021            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
1022            return dcac.getLinkCapabilitiesSync();
1023        } else {
1024            return new LinkCapabilities();
1025        }
1026    }
1027
1028    // tell all active apns of the current condition
1029    protected void notifyDataConnection(String reason) {
1030        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
1031            if (mDataEnabled[id]) {
1032                mPhone.notifyDataConnection(reason, apnIdToType(id));
1033            }
1034        }
1035        notifyOffApnsOfAvailability(reason);
1036    }
1037
1038    // a new APN has gone active and needs to send events to catch up with the
1039    // current condition
1040    private void notifyApnIdUpToCurrent(String reason, int apnId) {
1041        switch (mState) {
1042            case IDLE:
1043                break;
1044            case RETRYING:
1045            case CONNECTING:
1046            case SCANNING:
1047                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1048                        PhoneConstants.DataState.CONNECTING);
1049                break;
1050            case CONNECTED:
1051            case DISCONNECTING:
1052                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1053                        PhoneConstants.DataState.CONNECTING);
1054                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1055                        PhoneConstants.DataState.CONNECTED);
1056                break;
1057            default:
1058                // Ignore
1059                break;
1060        }
1061    }
1062
1063    // since we normally don't send info to a disconnected APN, we need to do this specially
1064    private void notifyApnIdDisconnected(String reason, int apnId) {
1065        mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1066                PhoneConstants.DataState.DISCONNECTED);
1067    }
1068
1069    // disabled apn's still need avail/unavail notificiations - send them out
1070    protected void notifyOffApnsOfAvailability(String reason) {
1071        if (DBG) log("notifyOffApnsOfAvailability - reason= " + reason);
1072        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
1073            if (!isApnIdEnabled(id)) {
1074                notifyApnIdDisconnected(reason, id);
1075            }
1076        }
1077    }
1078
1079    public boolean isApnTypeEnabled(String apnType) {
1080        if (apnType == null) {
1081            return false;
1082        } else {
1083            return isApnIdEnabled(apnTypeToId(apnType));
1084        }
1085    }
1086
1087    protected synchronized boolean isApnIdEnabled(int id) {
1088        if (id != DctConstants.APN_INVALID_ID) {
1089            return mDataEnabled[id];
1090        }
1091        return false;
1092    }
1093
1094    /**
1095     * Ensure that we are connected to an APN of the specified type.
1096     *
1097     * @param type the APN type (currently the only valid values are
1098     *            {@link PhoneConstants#APN_TYPE_MMS} and {@link PhoneConstants#APN_TYPE_SUPL})
1099     * @return Success is indicated by {@code Phone.APN_ALREADY_ACTIVE} or
1100     *         {@code Phone.APN_REQUEST_STARTED}. In the latter case, a
1101     *         broadcast will be sent by the ConnectivityManager when a
1102     *         connection to the APN has been established.
1103     */
1104    public synchronized int enableApnType(String type) {
1105        int id = apnTypeToId(type);
1106        if (id == DctConstants.APN_INVALID_ID) {
1107            return PhoneConstants.APN_REQUEST_FAILED;
1108        }
1109
1110        if (DBG) {
1111            log("enableApnType(" + type + "), isApnTypeActive = " + isApnTypeActive(type)
1112                    + ", isApnIdEnabled =" + isApnIdEnabled(id) + " and state = " + mState);
1113        }
1114
1115        if (!isApnTypeAvailable(type)) {
1116            if (DBG) log("enableApnType: not available, type=" + type);
1117            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1118        }
1119
1120        if (isApnIdEnabled(id)) {
1121            if (DBG) log("enableApnType: already active, type=" + type);
1122            return PhoneConstants.APN_ALREADY_ACTIVE;
1123        } else {
1124            setEnabled(id, true);
1125        }
1126        return PhoneConstants.APN_REQUEST_STARTED;
1127    }
1128
1129    /**
1130     * The APN of the specified type is no longer needed. Ensure that if use of
1131     * the default APN has not been explicitly disabled, we are connected to the
1132     * default APN.
1133     *
1134     * @param type the APN type. The only valid values are currently
1135     *            {@link PhoneConstants#APN_TYPE_MMS} and {@link PhoneConstants#APN_TYPE_SUPL}.
1136     * @return Success is indicated by {@code PhoneConstants.APN_ALREADY_ACTIVE} or
1137     *         {@code PhoneConstants.APN_REQUEST_STARTED}. In the latter case, a
1138     *         broadcast will be sent by the ConnectivityManager when a
1139     *         connection to the APN has been disconnected. A {@code
1140     *         PhoneConstants.APN_REQUEST_FAILED} is returned if the type parameter is
1141     *         invalid or if the apn wasn't enabled.
1142     */
1143    public synchronized int disableApnType(String type) {
1144        if (DBG) log("disableApnType(" + type + ")");
1145        int id = apnTypeToId(type);
1146        if (id == DctConstants.APN_INVALID_ID) {
1147            return PhoneConstants.APN_REQUEST_FAILED;
1148        }
1149        if (isApnIdEnabled(id)) {
1150            setEnabled(id, false);
1151            if (isApnTypeActive(PhoneConstants.APN_TYPE_DEFAULT)) {
1152                if (mDataEnabled[DctConstants.APN_DEFAULT_ID]) {
1153                    return PhoneConstants.APN_ALREADY_ACTIVE;
1154                } else {
1155                    return PhoneConstants.APN_REQUEST_STARTED;
1156                }
1157            } else {
1158                return PhoneConstants.APN_REQUEST_STARTED;
1159            }
1160        } else {
1161            return PhoneConstants.APN_REQUEST_FAILED;
1162        }
1163    }
1164
1165    protected void setEnabled(int id, boolean enable) {
1166        if (DBG) {
1167            log("setEnabled(" + id + ", " + enable + ") with old state = " + mDataEnabled[id]
1168                    + " and enabledCount = " + mEnabledCount);
1169        }
1170        Message msg = obtainMessage(DctConstants.EVENT_ENABLE_NEW_APN);
1171        msg.arg1 = id;
1172        msg.arg2 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
1173        sendMessage(msg);
1174    }
1175
1176    protected void onEnableApn(int apnId, int enabled) {
1177        if (DBG) {
1178            log("EVENT_APN_ENABLE_REQUEST apnId=" + apnId + ", apnType=" + apnIdToType(apnId) +
1179                    ", enabled=" + enabled + ", dataEnabled = " + mDataEnabled[apnId] +
1180                    ", enabledCount = " + mEnabledCount + ", isApnTypeActive = " +
1181                    isApnTypeActive(apnIdToType(apnId)));
1182        }
1183        if (enabled == DctConstants.ENABLED) {
1184            synchronized (this) {
1185                if (!mDataEnabled[apnId]) {
1186                    mDataEnabled[apnId] = true;
1187                    mEnabledCount++;
1188                }
1189            }
1190            String type = apnIdToType(apnId);
1191            if (!isApnTypeActive(type)) {
1192                mRequestedApnType = type;
1193                onEnableNewApn();
1194            } else {
1195                notifyApnIdUpToCurrent(Phone.REASON_APN_SWITCHED, apnId);
1196            }
1197        } else {
1198            // disable
1199            boolean didDisable = false;
1200            synchronized (this) {
1201                if (mDataEnabled[apnId]) {
1202                    mDataEnabled[apnId] = false;
1203                    mEnabledCount--;
1204                    didDisable = true;
1205                }
1206            }
1207            if (didDisable) {
1208                if ((mEnabledCount == 0) || (apnId == DctConstants.APN_DUN_ID)) {
1209                    mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
1210                    onCleanUpConnection(true, apnId, Phone.REASON_DATA_DISABLED);
1211                }
1212
1213                // send the disconnect msg manually, since the normal route wont send
1214                // it (it's not enabled)
1215                notifyApnIdDisconnected(Phone.REASON_DATA_DISABLED, apnId);
1216                if (mDataEnabled[DctConstants.APN_DEFAULT_ID] == true
1217                        && !isApnTypeActive(PhoneConstants.APN_TYPE_DEFAULT)) {
1218                    // TODO - this is an ugly way to restore the default conn - should be done
1219                    // by a real contention manager and policy that disconnects the lower pri
1220                    // stuff as enable requests come in and pops them back on as we disable back
1221                    // down to the lower pri stuff
1222                    mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
1223                    onEnableNewApn();
1224                }
1225            }
1226        }
1227    }
1228
1229    /**
1230     * Called when we switch APNs.
1231     *
1232     * mRequestedApnType is set prior to call
1233     * To be overridden.
1234     */
1235    protected void onEnableNewApn() {
1236    }
1237
1238    /**
1239     * Called when EVENT_RESET_DONE is received so goto
1240     * IDLE state and send notifications to those interested.
1241     *
1242     * TODO - currently unused.  Needs to be hooked into DataConnection cleanup
1243     * TODO - needs to pass some notion of which connection is reset..
1244     */
1245    protected void onResetDone(AsyncResult ar) {
1246        if (DBG) log("EVENT_RESET_DONE");
1247        String reason = null;
1248        if (ar.userObj instanceof String) {
1249            reason = (String) ar.userObj;
1250        }
1251        gotoIdleAndNotifyDataConnection(reason);
1252    }
1253
1254    /**
1255     * Prevent mobile data connections from being established, or once again
1256     * allow mobile data connections. If the state toggles, then either tear
1257     * down or set up data, as appropriate to match the new state.
1258     *
1259     * @param enable indicates whether to enable ({@code true}) or disable (
1260     *            {@code false}) data
1261     * @return {@code true} if the operation succeeded
1262     */
1263    public boolean setInternalDataEnabled(boolean enable) {
1264        if (DBG)
1265            log("setInternalDataEnabled(" + enable + ")");
1266
1267        Message msg = obtainMessage(DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE);
1268        msg.arg1 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
1269        sendMessage(msg);
1270        return true;
1271    }
1272
1273    protected void onSetInternalDataEnabled(boolean enabled) {
1274        synchronized (mDataEnabledLock) {
1275            mInternalDataEnabled = enabled;
1276            if (enabled) {
1277                log("onSetInternalDataEnabled: changed to enabled, try to setup data call");
1278                onTrySetupData(Phone.REASON_DATA_ENABLED);
1279            } else {
1280                log("onSetInternalDataEnabled: changed to disabled, cleanUpAllConnections");
1281                cleanUpAllConnections(null);
1282            }
1283        }
1284    }
1285
1286    public void cleanUpAllConnections(String cause) {
1287        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS);
1288        msg.obj = cause;
1289        sendMessage(msg);
1290    }
1291
1292    public abstract boolean isDisconnected();
1293
1294    protected void onSetUserDataEnabled(boolean enabled) {
1295        synchronized (mDataEnabledLock) {
1296            final boolean prevEnabled = getAnyDataEnabled();
1297            if (mUserDataEnabled != enabled) {
1298                mUserDataEnabled = enabled;
1299                Settings.Global.putInt(mPhone.getContext().getContentResolver(),
1300                        Settings.Global.MOBILE_DATA, enabled ? 1 : 0);
1301                if (getDataOnRoamingEnabled() == false &&
1302                        mPhone.getServiceState().getRoaming() == true) {
1303                    if (enabled) {
1304                        notifyOffApnsOfAvailability(Phone.REASON_ROAMING_ON);
1305                    } else {
1306                        notifyOffApnsOfAvailability(Phone.REASON_DATA_DISABLED);
1307                    }
1308                }
1309                if (prevEnabled != getAnyDataEnabled()) {
1310                    if (!prevEnabled) {
1311                        onTrySetupData(Phone.REASON_DATA_ENABLED);
1312                    } else {
1313                        onCleanUpAllConnections(Phone.REASON_DATA_DISABLED);
1314                    }
1315                }
1316            }
1317        }
1318    }
1319
1320    protected void onSetDependencyMet(String apnType, boolean met) {
1321    }
1322
1323    protected void onSetPolicyDataEnabled(boolean enabled) {
1324        synchronized (mDataEnabledLock) {
1325            final boolean prevEnabled = getAnyDataEnabled();
1326            if (sPolicyDataEnabled != enabled) {
1327                sPolicyDataEnabled = enabled;
1328                if (prevEnabled != getAnyDataEnabled()) {
1329                    if (!prevEnabled) {
1330                        onTrySetupData(Phone.REASON_DATA_ENABLED);
1331                    } else {
1332                        onCleanUpAllConnections(Phone.REASON_DATA_DISABLED);
1333                    }
1334                }
1335            }
1336        }
1337    }
1338
1339    protected String getReryConfig(boolean forDefault) {
1340        int nt = mPhone.getServiceState().getNetworkType();
1341
1342        if ((nt == TelephonyManager.NETWORK_TYPE_CDMA) ||
1343            (nt == TelephonyManager.NETWORK_TYPE_1xRTT) ||
1344            (nt == TelephonyManager.NETWORK_TYPE_EVDO_0) ||
1345            (nt == TelephonyManager.NETWORK_TYPE_EVDO_A) ||
1346            (nt == TelephonyManager.NETWORK_TYPE_EVDO_B) ||
1347            (nt == TelephonyManager.NETWORK_TYPE_EHRPD)) {
1348            // CDMA variant
1349            return SystemProperties.get("ro.cdma.data_retry_config");
1350        } else {
1351            // Use GSM varient for all others.
1352            if (forDefault) {
1353                return SystemProperties.get("ro.gsm.data_retry_config");
1354            } else {
1355                return SystemProperties.get("ro.gsm.2nd_data_retry_config");
1356            }
1357        }
1358    }
1359
1360    protected void resetPollStats() {
1361        mTxPkts = -1;
1362        mRxPkts = -1;
1363        mNetStatPollPeriod = POLL_NETSTAT_MILLIS;
1364    }
1365
1366    protected abstract DctConstants.State getOverallState();
1367
1368    protected void startNetStatPoll() {
1369        if (getOverallState() == DctConstants.State.CONNECTED
1370                && mNetStatPollEnabled == false) {
1371            if (DBG) log("startNetStatPoll");
1372            resetPollStats();
1373            mNetStatPollEnabled = true;
1374            mPollNetStat.run();
1375        }
1376    }
1377
1378    protected void stopNetStatPoll() {
1379        mNetStatPollEnabled = false;
1380        removeCallbacks(mPollNetStat);
1381        if (DBG) log("stopNetStatPoll");
1382    }
1383
1384    public void updateDataActivity() {
1385        long sent, received;
1386
1387        DctConstants.Activity newActivity;
1388
1389        TxRxSum preTxRxSum = new TxRxSum(mTxPkts, mRxPkts);
1390        TxRxSum curTxRxSum = new TxRxSum();
1391        curTxRxSum.updateTxRxSum();
1392        mTxPkts = curTxRxSum.txPkts;
1393        mRxPkts = curTxRxSum.rxPkts;
1394
1395        if (VDBG) {
1396            log("updateDataActivity: curTxRxSum=" + curTxRxSum + " preTxRxSum=" + preTxRxSum);
1397        }
1398
1399        if (mNetStatPollEnabled && (preTxRxSum.txPkts > 0 || preTxRxSum.rxPkts > 0)) {
1400            sent = mTxPkts - preTxRxSum.txPkts;
1401            received = mRxPkts - preTxRxSum.rxPkts;
1402
1403            if (VDBG)
1404                log("updateDataActivity: sent=" + sent + " received=" + received);
1405            if (sent > 0 && received > 0) {
1406                newActivity = DctConstants.Activity.DATAINANDOUT;
1407            } else if (sent > 0 && received == 0) {
1408                newActivity = DctConstants.Activity.DATAOUT;
1409            } else if (sent == 0 && received > 0) {
1410                newActivity = DctConstants.Activity.DATAIN;
1411            } else {
1412                newActivity = (mActivity == DctConstants.Activity.DORMANT) ?
1413                        mActivity : DctConstants.Activity.NONE;
1414            }
1415
1416            if (mActivity != newActivity && mIsScreenOn) {
1417                if (VDBG)
1418                    log("updateDataActivity: newActivity=" + newActivity);
1419                mActivity = newActivity;
1420                mPhone.notifyDataActivity();
1421            }
1422        }
1423    }
1424
1425    // Recovery action taken in case of data stall
1426    protected static class RecoveryAction {
1427        public static final int GET_DATA_CALL_LIST      = 0;
1428        public static final int CLEANUP                 = 1;
1429        public static final int REREGISTER              = 2;
1430        public static final int RADIO_RESTART           = 3;
1431        public static final int RADIO_RESTART_WITH_PROP = 4;
1432
1433        private static boolean isAggressiveRecovery(int value) {
1434            return ((value == RecoveryAction.CLEANUP) ||
1435                    (value == RecoveryAction.REREGISTER) ||
1436                    (value == RecoveryAction.RADIO_RESTART) ||
1437                    (value == RecoveryAction.RADIO_RESTART_WITH_PROP));
1438        }
1439    }
1440
1441    public int getRecoveryAction() {
1442        int action = Settings.System.getInt(mPhone.getContext().getContentResolver(),
1443                "radio.data.stall.recovery.action", RecoveryAction.GET_DATA_CALL_LIST);
1444        if (VDBG_STALL) log("getRecoveryAction: " + action);
1445        return action;
1446    }
1447    public void putRecoveryAction(int action) {
1448        Settings.System.putInt(mPhone.getContext().getContentResolver(),
1449                "radio.data.stall.recovery.action", action);
1450        if (VDBG_STALL) log("putRecoveryAction: " + action);
1451    }
1452
1453    protected boolean isConnected() {
1454        return false;
1455    }
1456
1457    protected void doRecovery() {
1458        if (getOverallState() == DctConstants.State.CONNECTED) {
1459            // Go through a series of recovery steps, each action transitions to the next action
1460            int recoveryAction = getRecoveryAction();
1461            switch (recoveryAction) {
1462            case RecoveryAction.GET_DATA_CALL_LIST:
1463                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_GET_DATA_CALL_LIST,
1464                        mSentSinceLastRecv);
1465                if (DBG) log("doRecovery() get data call list");
1466                mPhone.mCi.getDataCallList(obtainMessage(DctConstants.EVENT_DATA_STATE_CHANGED));
1467                putRecoveryAction(RecoveryAction.CLEANUP);
1468                break;
1469            case RecoveryAction.CLEANUP:
1470                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_CLEANUP, mSentSinceLastRecv);
1471                if (DBG) log("doRecovery() cleanup all connections");
1472                cleanUpAllConnections(Phone.REASON_PDP_RESET);
1473                putRecoveryAction(RecoveryAction.REREGISTER);
1474                break;
1475            case RecoveryAction.REREGISTER:
1476                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_REREGISTER,
1477                        mSentSinceLastRecv);
1478                if (DBG) log("doRecovery() re-register");
1479                mPhone.getServiceStateTracker().reRegisterNetwork(null);
1480                putRecoveryAction(RecoveryAction.RADIO_RESTART);
1481                break;
1482            case RecoveryAction.RADIO_RESTART:
1483                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART,
1484                        mSentSinceLastRecv);
1485                if (DBG) log("restarting radio");
1486                putRecoveryAction(RecoveryAction.RADIO_RESTART_WITH_PROP);
1487                restartRadio();
1488                break;
1489            case RecoveryAction.RADIO_RESTART_WITH_PROP:
1490                // This is in case radio restart has not recovered the data.
1491                // It will set an additional "gsm.radioreset" property to tell
1492                // RIL or system to take further action.
1493                // The implementation of hard reset recovery action is up to OEM product.
1494                // Once RADIO_RESET property is consumed, it is expected to set back
1495                // to false by RIL.
1496                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART_WITH_PROP, -1);
1497                if (DBG) log("restarting radio with gsm.radioreset to true");
1498                SystemProperties.set(RADIO_RESET_PROPERTY, "true");
1499                // give 1 sec so property change can be notified.
1500                try {
1501                    Thread.sleep(1000);
1502                } catch (InterruptedException e) {}
1503                restartRadio();
1504                putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1505                break;
1506            default:
1507                throw new RuntimeException("doRecovery: Invalid recoveryAction=" +
1508                    recoveryAction);
1509            }
1510            mSentSinceLastRecv = 0;
1511        }
1512    }
1513
1514    private void updateDataStallInfo() {
1515        long sent, received;
1516
1517        TxRxSum preTxRxSum = new TxRxSum(mDataStallTxRxSum);
1518        mDataStallTxRxSum.updateTxRxSum();
1519
1520        if (VDBG_STALL) {
1521            log("updateDataStallInfo: mDataStallTxRxSum=" + mDataStallTxRxSum +
1522                    " preTxRxSum=" + preTxRxSum);
1523        }
1524
1525        sent = mDataStallTxRxSum.txPkts - preTxRxSum.txPkts;
1526        received = mDataStallTxRxSum.rxPkts - preTxRxSum.rxPkts;
1527
1528        if (RADIO_TESTS) {
1529            if (SystemProperties.getBoolean("radio.test.data.stall", false)) {
1530                log("updateDataStallInfo: radio.test.data.stall true received = 0;");
1531                received = 0;
1532            }
1533        }
1534        if ( sent > 0 && received > 0 ) {
1535            if (VDBG_STALL) log("updateDataStallInfo: IN/OUT");
1536            mSentSinceLastRecv = 0;
1537            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1538        } else if (sent > 0 && received == 0) {
1539            if (mPhone.getState() == PhoneConstants.State.IDLE) {
1540                mSentSinceLastRecv += sent;
1541            } else {
1542                mSentSinceLastRecv = 0;
1543            }
1544            if (DBG) {
1545                log("updateDataStallInfo: OUT sent=" + sent +
1546                        " mSentSinceLastRecv=" + mSentSinceLastRecv);
1547            }
1548        } else if (sent == 0 && received > 0) {
1549            if (VDBG_STALL) log("updateDataStallInfo: IN");
1550            mSentSinceLastRecv = 0;
1551            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1552        } else {
1553            if (VDBG_STALL) log("updateDataStallInfo: NONE");
1554        }
1555    }
1556
1557    protected void onDataStallAlarm(int tag) {
1558        if (mDataStallAlarmTag != tag) {
1559            if (DBG) {
1560                log("onDataStallAlarm: ignore, tag=" + tag + " expecting " + mDataStallAlarmTag);
1561            }
1562            return;
1563        }
1564        updateDataStallInfo();
1565
1566        int hangWatchdogTrigger = Settings.Global.getInt(mResolver,
1567                Settings.Global.PDP_WATCHDOG_TRIGGER_PACKET_COUNT,
1568                NUMBER_SENT_PACKETS_OF_HANG);
1569
1570        boolean suspectedStall = DATA_STALL_NOT_SUSPECTED;
1571        if (mSentSinceLastRecv >= hangWatchdogTrigger) {
1572            if (DBG) {
1573                log("onDataStallAlarm: tag=" + tag + " do recovery action=" + getRecoveryAction());
1574            }
1575            suspectedStall = DATA_STALL_SUSPECTED;
1576            sendMessage(obtainMessage(DctConstants.EVENT_DO_RECOVERY));
1577        } else {
1578            if (VDBG_STALL) {
1579                log("onDataStallAlarm: tag=" + tag + " Sent " + String.valueOf(mSentSinceLastRecv) +
1580                    " pkts since last received, < watchdogTrigger=" + hangWatchdogTrigger);
1581            }
1582        }
1583        startDataStallAlarm(suspectedStall);
1584    }
1585
1586    protected void startDataStallAlarm(boolean suspectedStall) {
1587        int nextAction = getRecoveryAction();
1588        int delayInMs;
1589
1590        if (mDataStallDetectionEnabled && getOverallState() == DctConstants.State.CONNECTED) {
1591            // If screen is on or data stall is currently suspected, set the alarm
1592            // with an aggresive timeout.
1593            if (mIsScreenOn || suspectedStall || RecoveryAction.isAggressiveRecovery(nextAction)) {
1594                delayInMs = Settings.Global.getInt(mResolver,
1595                        Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
1596                        DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1597            } else {
1598                delayInMs = Settings.Global.getInt(mResolver,
1599                        Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
1600                        DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1601            }
1602
1603            mDataStallAlarmTag += 1;
1604            if (VDBG_STALL) {
1605                log("startDataStallAlarm: tag=" + mDataStallAlarmTag +
1606                        " delay=" + (delayInMs / 1000) + "s");
1607            }
1608            Intent intent = new Intent(INTENT_DATA_STALL_ALARM);
1609            intent.putExtra(DATA_STALL_ALARM_TAG_EXTRA, mDataStallAlarmTag);
1610            mDataStallAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
1611                    PendingIntent.FLAG_UPDATE_CURRENT);
1612            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1613                    SystemClock.elapsedRealtime() + delayInMs, mDataStallAlarmIntent);
1614        } else {
1615            if (VDBG_STALL) {
1616                log("startDataStallAlarm: NOT started, no connection tag=" + mDataStallAlarmTag);
1617            }
1618        }
1619    }
1620
1621    protected void stopDataStallAlarm() {
1622        if (VDBG_STALL) {
1623            log("stopDataStallAlarm: current tag=" + mDataStallAlarmTag +
1624                    " mDataStallAlarmIntent=" + mDataStallAlarmIntent);
1625        }
1626        mDataStallAlarmTag += 1;
1627        if (mDataStallAlarmIntent != null) {
1628            mAlarmManager.cancel(mDataStallAlarmIntent);
1629            mDataStallAlarmIntent = null;
1630        }
1631    }
1632
1633    protected void restartDataStallAlarm() {
1634        if (isConnected() == false) return;
1635        // To be called on screen status change.
1636        // Do not cancel the alarm if it is set with aggressive timeout.
1637        int nextAction = getRecoveryAction();
1638
1639        if (RecoveryAction.isAggressiveRecovery(nextAction)) {
1640            if (DBG) log("restartDataStallAlarm: action is pending. not resetting the alarm.");
1641            return;
1642        }
1643        if (VDBG_STALL) log("restartDataStallAlarm: stop then start.");
1644        stopDataStallAlarm();
1645        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1646    }
1647
1648    protected void setInitialAttachApn() {
1649        ApnSetting iaApnSetting = null;
1650        ApnSetting defaultApnSetting = null;
1651        ApnSetting firstApnSetting = null;
1652
1653        log("setInitialApn: E mPreferredApn=" + mPreferredApn);
1654
1655        if (mAllApnSettings != null && !mAllApnSettings.isEmpty()) {
1656            firstApnSetting = mAllApnSettings.get(0);
1657            log("setInitialApn: firstApnSetting=" + firstApnSetting);
1658
1659            // Search for Initial APN setting and the first apn that can handle default
1660            for (ApnSetting apn : mAllApnSettings) {
1661                // Can't use apn.canHandleType(), as that returns true for APNs that have no type.
1662                if (ArrayUtils.contains(apn.types, PhoneConstants.APN_TYPE_IA)) {
1663                    // The Initial Attach APN is highest priority so use it if there is one
1664                    log("setInitialApn: iaApnSetting=" + apn);
1665                    iaApnSetting = apn;
1666                    break;
1667                } else if ((defaultApnSetting == null)
1668                        && (apn.canHandleType(PhoneConstants.APN_TYPE_DEFAULT))) {
1669                    // Use the first default apn if no better choice
1670                    log("setInitialApn: defaultApnSetting=" + apn);
1671                    defaultApnSetting = apn;
1672                }
1673            }
1674        }
1675
1676        // The priority of apn candidates from highest to lowest is:
1677        //   1) APN_TYPE_IA (Inital Attach)
1678        //   2) mPreferredApn, i.e. the current preferred apn
1679        //   3) The first apn that than handle APN_TYPE_DEFAULT
1680        //   4) The first APN we can find.
1681
1682        ApnSetting initialAttachApnSetting = null;
1683        if (iaApnSetting != null) {
1684            if (DBG) log("setInitialAttachApn: using iaApnSetting");
1685            initialAttachApnSetting = iaApnSetting;
1686        } else if (mPreferredApn != null) {
1687            if (DBG) log("setInitialAttachApn: using mPreferredApn");
1688            initialAttachApnSetting = mPreferredApn;
1689        } else if (defaultApnSetting != null) {
1690            if (DBG) log("setInitialAttachApn: using defaultApnSetting");
1691            initialAttachApnSetting = defaultApnSetting;
1692        } else if (firstApnSetting != null) {
1693            if (DBG) log("setInitialAttachApn: using firstApnSetting");
1694            initialAttachApnSetting = firstApnSetting;
1695        }
1696
1697        if (initialAttachApnSetting == null) {
1698            if (DBG) log("setInitialAttachApn: X There in no available apn");
1699        } else {
1700            if (DBG) log("setInitialAttachApn: X selected Apn=" + initialAttachApnSetting);
1701
1702            mPhone.mCi.setInitialAttachApn(initialAttachApnSetting.apn,
1703                    initialAttachApnSetting.protocol, initialAttachApnSetting.authType,
1704                    initialAttachApnSetting.user, initialAttachApnSetting.password, null);
1705        }
1706    }
1707
1708    protected void onActionIntentProvisioningApnAlarm(Intent intent) {
1709        if (DBG) log("onActionIntentProvisioningApnAlarm: action=" + intent.getAction());
1710        Message msg = obtainMessage(DctConstants.EVENT_PROVISIONING_APN_ALARM,
1711                intent.getAction());
1712        msg.arg1 = intent.getIntExtra(PROVISIONING_APN_ALARM_TAG_EXTRA, 0);
1713        sendMessage(msg);
1714    }
1715
1716    protected void startProvisioningApnAlarm() {
1717        int delayInMs = Settings.Global.getInt(mResolver,
1718                                Settings.Global.PROVISIONING_APN_ALARM_DELAY_IN_MS,
1719                                PROVISIONING_APN_ALARM_DELAY_IN_MS_DEFAULT);
1720        if (Build.IS_DEBUGGABLE) {
1721            // Allow debug code to use a system property to provide another value
1722            String delayInMsStrg = Integer.toString(delayInMs);
1723            delayInMsStrg = System.getProperty(DEBUG_PROV_APN_ALARM, delayInMsStrg);
1724            try {
1725                delayInMs = Integer.parseInt(delayInMsStrg);
1726            } catch (NumberFormatException e) {
1727                loge("startProvisioningApnAlarm: e=" + e);
1728            }
1729        }
1730        mProvisioningApnAlarmTag += 1;
1731        if (DBG) {
1732            log("startProvisioningApnAlarm: tag=" + mProvisioningApnAlarmTag +
1733                    " delay=" + (delayInMs / 1000) + "s");
1734        }
1735        Intent intent = new Intent(INTENT_PROVISIONING_APN_ALARM);
1736        intent.putExtra(PROVISIONING_APN_ALARM_TAG_EXTRA, mProvisioningApnAlarmTag);
1737        mProvisioningApnAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
1738                PendingIntent.FLAG_UPDATE_CURRENT);
1739        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1740                SystemClock.elapsedRealtime() + delayInMs, mProvisioningApnAlarmIntent);
1741    }
1742
1743    protected void stopProvisioningApnAlarm() {
1744        if (DBG) {
1745            log("stopProvisioningApnAlarm: current tag=" + mProvisioningApnAlarmTag +
1746                    " mProvsioningApnAlarmIntent=" + mProvisioningApnAlarmIntent);
1747        }
1748        mProvisioningApnAlarmTag += 1;
1749        if (mProvisioningApnAlarmIntent != null) {
1750            mAlarmManager.cancel(mProvisioningApnAlarmIntent);
1751            mProvisioningApnAlarmIntent = null;
1752        }
1753    }
1754
1755    void sendCleanUpConnection(boolean tearDown, ApnContext apnContext) {
1756        if (DBG)log("sendCleanUpConnection: tearDown=" + tearDown + " apnContext=" + apnContext);
1757        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_CONNECTION);
1758        msg.arg1 = tearDown ? 1 : 0;
1759        msg.arg2 = 0;
1760        msg.obj = apnContext;
1761        sendMessage(msg);
1762    }
1763
1764    void sendRestartRadio() {
1765        if (DBG)log("sendRestartRadio:");
1766        Message msg = obtainMessage(DctConstants.EVENT_RESTART_RADIO);
1767        sendMessage(msg);
1768    }
1769
1770    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1771        pw.println("DataConnectionTrackerBase:");
1772        pw.println(" RADIO_TESTS=" + RADIO_TESTS);
1773        pw.println(" mInternalDataEnabled=" + mInternalDataEnabled);
1774        pw.println(" mUserDataEnabled=" + mUserDataEnabled);
1775        pw.println(" sPolicyDataEnabed=" + sPolicyDataEnabled);
1776        pw.println(" mDataEnabled:");
1777        for(int i=0; i < mDataEnabled.length; i++) {
1778            pw.printf("  mDataEnabled[%d]=%b\n", i, mDataEnabled[i]);
1779        }
1780        pw.flush();
1781        pw.println(" mEnabledCount=" + mEnabledCount);
1782        pw.println(" mRequestedApnType=" + mRequestedApnType);
1783        pw.println(" mPhone=" + mPhone.getPhoneName());
1784        pw.println(" mActivity=" + mActivity);
1785        pw.println(" mState=" + mState);
1786        pw.println(" mTxPkts=" + mTxPkts);
1787        pw.println(" mRxPkts=" + mRxPkts);
1788        pw.println(" mNetStatPollPeriod=" + mNetStatPollPeriod);
1789        pw.println(" mNetStatPollEnabled=" + mNetStatPollEnabled);
1790        pw.println(" mDataStallTxRxSum=" + mDataStallTxRxSum);
1791        pw.println(" mDataStallAlarmTag=" + mDataStallAlarmTag);
1792        pw.println(" mDataStallDetectionEanbled=" + mDataStallDetectionEnabled);
1793        pw.println(" mSentSinceLastRecv=" + mSentSinceLastRecv);
1794        pw.println(" mNoRecvPollCount=" + mNoRecvPollCount);
1795        pw.println(" mResolver=" + mResolver);
1796        pw.println(" mIsWifiConnected=" + mIsWifiConnected);
1797        pw.println(" mReconnectIntent=" + mReconnectIntent);
1798        pw.println(" mCidActive=" + mCidActive);
1799        pw.println(" mAutoAttachOnCreation=" + mAutoAttachOnCreation);
1800        pw.println(" mIsScreenOn=" + mIsScreenOn);
1801        pw.println(" mUniqueIdGenerator=" + mUniqueIdGenerator);
1802        pw.flush();
1803        pw.println(" ***************************************");
1804        DcController dcc = mDcc;
1805        if (dcc != null) {
1806            dcc.dump(fd, pw, args);
1807        } else {
1808            pw.println(" mDcc=null");
1809        }
1810        pw.println(" ***************************************");
1811        HashMap<Integer, DataConnection> dcs = mDataConnections;
1812        if (dcs != null) {
1813            Set<Entry<Integer, DataConnection> > mDcSet = mDataConnections.entrySet();
1814            pw.println(" mDataConnections: count=" + mDcSet.size());
1815            for (Entry<Integer, DataConnection> entry : mDcSet) {
1816                pw.printf(" *** mDataConnection[%d] \n", entry.getKey());
1817                entry.getValue().dump(fd, pw, args);
1818            }
1819        } else {
1820            pw.println("mDataConnections=null");
1821        }
1822        pw.println(" ***************************************");
1823        pw.flush();
1824        HashMap<String, Integer> apnToDcId = mApnToDataConnectionId;
1825        if (apnToDcId != null) {
1826            Set<Entry<String, Integer>> apnToDcIdSet = apnToDcId.entrySet();
1827            pw.println(" mApnToDataConnectonId size=" + apnToDcIdSet.size());
1828            for (Entry<String, Integer> entry : apnToDcIdSet) {
1829                pw.printf(" mApnToDataConnectonId[%s]=%d\n", entry.getKey(), entry.getValue());
1830            }
1831        } else {
1832            pw.println("mApnToDataConnectionId=null");
1833        }
1834        pw.println(" ***************************************");
1835        pw.flush();
1836        ConcurrentHashMap<String, ApnContext> apnCtxs = mApnContexts;
1837        if (apnCtxs != null) {
1838            Set<Entry<String, ApnContext>> apnCtxsSet = apnCtxs.entrySet();
1839            pw.println(" mApnContexts size=" + apnCtxsSet.size());
1840            for (Entry<String, ApnContext> entry : apnCtxsSet) {
1841                entry.getValue().dump(fd, pw, args);
1842            }
1843            pw.println(" ***************************************");
1844        } else {
1845            pw.println(" mApnContexts=null");
1846        }
1847        pw.flush();
1848        pw.println(" mActiveApn=" + mActiveApn);
1849        ArrayList<ApnSetting> apnSettings = mAllApnSettings;
1850        if (apnSettings != null) {
1851            pw.println(" mAllApnSettings size=" + apnSettings.size());
1852            for (int i=0; i < apnSettings.size(); i++) {
1853                pw.printf(" mAllApnSettings[%d]: %s\n", i, apnSettings.get(i));
1854            }
1855            pw.flush();
1856        } else {
1857            pw.println(" mAllApnSettings=null");
1858        }
1859        pw.println(" mPreferredApn=" + mPreferredApn);
1860        pw.println(" mIsPsRestricted=" + mIsPsRestricted);
1861        pw.println(" mIsDisposed=" + mIsDisposed);
1862        pw.println(" mIntentReceiver=" + mIntentReceiver);
1863        pw.println(" mDataRoamingSettingObserver=" + mDataRoamingSettingObserver);
1864        pw.flush();
1865    }
1866}
1867